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

@ -11,7 +11,7 @@ import { z } from 'zod';
import type { DraftCard, DraftQuestion } from '../../shared/content.ts';
import { draftsFromValue } from '../../shared/importer.ts';
import type { DB } from '../db.ts';
import { badRequest, notFound, type AppContext } from '../http.ts';
import { badRequest, HttpError, notFound, type AppContext } from '../http.ts';
import { getAppSettings } from '../settings.ts';
import { createAttempt, missedQuestionIds } from '../services/attempts.ts';
import { createClass, createFolder, getClass, getDeck, getQuiz, listCards, listQuestions, resolveFolder } from '../services/content.ts';
@ -52,6 +52,16 @@ export type AssistantEvent =
export interface AssistantContext {
classId?: string | null;
documentIds?: string[];
/** Materials the user tagged with @ in this message. */
items?: TaggedItem[];
}
export const TAG_KINDS = ['quiz', 'deck', 'note', 'document', 'folder'] as const;
export type TagKind = (typeof TAG_KINDS)[number];
export interface TaggedItem {
kind: TagKind;
id: string;
title: string;
}
interface ToolRun {
@ -483,7 +493,7 @@ const TOOLS: ToolSpec[] = [
type: 'array',
items: obj(
{
type: { type: 'string', enum: ['single', 'multi'] },
type: { type: 'string', enum: ['single', 'multi', 'numeric'], description: 'numeric = the student types a number (calculations); its options hold only the correct answer, e.g. "12.5 mL".' },
stem: S,
options: { type: 'array', items: obj({ text: S, correct: { type: 'boolean' }, why: S }, ['text', 'correct']) },
rationale: S,
@ -744,6 +754,8 @@ interface MessageRow {
interface MessageMeta {
hidden?: boolean;
toolResults?: boolean;
/** Materials tagged in a user message. */
tags?: TaggedItem[];
tools?: ToolActivity[];
ui?: UiItem[];
model?: string;
@ -754,6 +766,7 @@ export interface DisplayMessage {
id: number;
role: 'user' | 'assistant';
text: string;
tags?: TaggedItem[];
tools: ToolActivity[];
ui: UiItem[];
model?: string;
@ -773,7 +786,7 @@ export function displayMessages(db: DB, conversationId: string): DisplayMessage[
const text = msg.content.filter((p) => p.type === 'text').map((p) => (p as { text: string }).text).join('');
if (row.role === 'user') {
current = null;
out.push({ id: row.id, role: 'user', text, tools: [], ui: [], createdAt: row.created_at });
out.push({ id: row.id, role: 'user', text, tools: [], ui: [], createdAt: row.created_at, ...(meta.tags?.length ? { tags: meta.tags } : {}) });
continue;
}
if (!current) {
@ -857,6 +870,20 @@ function systemPrompt(app: AppContext, context: AssistantContext): string {
const docs = db.all<{ id: string; title: string }>(`SELECT id, title FROM documents WHERE id IN (${context.documentIds.map(() => '?').join(',')})`, ...context.documentIds);
if (docs.length) lines.push(`The user has these documents in focus: ${docs.map((d) => `"${d.title}" (id ${d.id})`).join(', ')}. Questions like "summarise this" refer to them.`);
}
if (context.items?.length) {
const how: Record<TagKind, string> = {
quiz: 'open it with get_quiz',
deck: 'open it with get_deck',
note: 'read it with read_note',
document: 'search it with search_documents or read it with read_document; pass its id as a source when generating',
folder: 'list its contents with list_materials',
};
lines.push(
`In their latest message the user tagged these materials, so "this", "these" and similar words refer to them. Use the ids directly instead of searching for them:\n${context.items
.map((i) => `- ${i.kind} "${i.title}" — id ${i.id}${TAG_URL[i.kind] ? `, link ${TAG_URL[i.kind]}${i.id}` : ''} (${how[i.kind]})`)
.join('\n')}`,
);
}
lines.push(
`How to work:
- Use tools instead of guessing. To answer questions about their material, search or read the documents first and base the answer on what you find.
@ -877,10 +904,131 @@ function systemPrompt(app: AppContext, context: AssistantContext): string {
export const assistantRequestSchema = z.object({
conversationId: z.string().nullish(),
message: z.string().trim().min(1).max(20_000),
context: z.object({ classId: z.string().nullish(), documentIds: z.array(z.string()).max(20).optional() }).optional(),
context: z
.object({
classId: z.string().nullish(),
documentIds: z.array(z.string()).max(20).optional(),
items: z.array(z.object({ kind: z.enum(TAG_KINDS), id: z.string().max(60) })).max(20).optional(),
})
.optional(),
modelId: z.string().nullish(),
});
/** App paths for linking tagged items in answers (folders have no page of their own). */
const TAG_URL: Record<TagKind, string> = { quiz: '/quizzes/', deck: '/decks/', note: '/notes/', document: '/documents/', folder: '' };
const TAG_TABLE: Record<TagKind, { table: string; title: string }> = {
quiz: { table: 'quizzes', title: 'title' },
deck: { table: 'decks', title: 'title' },
note: { table: 'notes', title: 'title' },
document: { table: 'documents', title: 'title' },
folder: { table: 'folders', title: 'name' },
};
/** Looks tagged items up so the model (and the transcript) get their real titles; unknown ids are dropped. */
function resolveTags(db: DB, items: { kind: TagKind; id: string }[] | undefined): TaggedItem[] {
const out: TaggedItem[] = [];
for (const i of items ?? []) {
const meta = TAG_TABLE[i.kind];
const row = db.get<{ title: string }>(`SELECT ${meta.title} AS title FROM ${meta.table} WHERE id = ?`, i.id);
if (row && !out.some((o) => o.kind === i.kind && o.id === i.id)) out.push({ kind: i.kind, id: i.id, title: row.title });
}
return out;
}
/** Library items the user can tag with @: one class's materials, or a title search across everything. */
export function mentionables(db: DB, opts: { classId?: string | null; q?: string }): (TaggedItem & { className: string; classColor: string; folderName?: string })[] {
const q = (opts.q ?? '').trim().slice(0, 80);
const like = `%${q.replace(/[\\%_]/g, (m) => `\\${m}`)}%`;
const out: (TaggedItem & { className: string; classColor: string; folderName?: string })[] = [];
const limit = opts.classId ? 300 : 12;
for (const kind of TAG_KINDS) {
const meta = TAG_TABLE[kind];
const where = [opts.classId ? 't.class_id = ?' : '1 = 1', q ? `t.${meta.title} LIKE ? ESCAPE '\\'` : '1 = 1'];
const params = [...(opts.classId ? [opts.classId] : []), ...(q ? [like] : [])];
const folderJoin = kind === 'folder' ? '' : 'LEFT JOIN folders f ON f.id = t.folder_id';
const folderCol = kind === 'folder' ? "'' AS folder_name" : 'f.name AS folder_name';
const rows = db.all<{ id: string; title: string; class_name: string; class_color: string; folder_name: string | null }>(
`SELECT t.id, t.${meta.title} AS title, k.name AS class_name, k.color AS class_color, ${folderCol}
FROM ${meta.table} t JOIN classes k ON k.id = t.class_id ${folderJoin}
WHERE ${where.join(' AND ')} ${kind === 'document' ? "AND t.status = 'ready'" : ''}
ORDER BY t.updated_at DESC LIMIT ?`,
...params,
limit,
);
for (const r of rows) out.push({ kind, id: r.id, title: r.title, className: r.class_name, classColor: r.class_color, ...(r.folder_name ? { folderName: r.folder_name } : {}) });
}
return out;
}
/* ------------------------------ running turns ------------------------------ */
/**
* A turn keeps running on the server when the browser disconnects (the user leaves the
* page, closes the drawer, switches to another conversation). Its events are buffered so a
* client that comes back can replay them and follow along; only "Stop" cancels it.
*/
interface LiveTurn {
events: AssistantEvent[];
listeners: Set<(event: AssistantEvent) => void>;
controller: AbortController;
}
const live = new Map<string, LiveTurn>();
export function isTurnRunning(conversationId: string): boolean {
return live.has(conversationId);
}
/** Replays the running turn's events, then streams the rest. Returns an unsubscribe function, or null when nothing is running. */
export function followTurn(conversationId: string, listener: (event: AssistantEvent) => void): (() => void) | null {
const turn = live.get(conversationId);
if (!turn) return null;
for (const e of turn.events) listener(e);
turn.listeners.add(listener);
return () => turn.listeners.delete(listener);
}
export function stopTurn(conversationId: string): boolean {
const turn = live.get(conversationId);
if (!turn) return false;
turn.controller.abort();
return true;
}
/**
* Starts a turn in the background and returns its conversation id at once. Problems that
* prevent the turn from starting (no model configured, unknown model, a turn already
* running in this conversation) throw here, before anything is saved.
*/
export function startAssistantTurn(app: AppContext, input: z.input<typeof assistantRequestSchema>): { conversationId: string } {
const req = assistantRequestSchema.parse(input);
if (req.conversationId && live.has(req.conversationId)) throw new HttpError(409, 'busy', 'The assistant is still answering in this conversation. Wait for it or press Stop.');
resolveModel(app, 'chat', req.modelId);
const controller = new AbortController();
const turn: LiveTurn = { events: [], listeners: new Set(), controller };
let id = '';
const emit = (event: AssistantEvent) => {
turn.events.push(event);
for (const fn of turn.listeners) fn(event);
};
const started = runAssistantTurn(app, req, emit, controller.signal, (conversationId) => {
id = conversationId;
live.set(conversationId, turn);
});
void started
.catch((err) => {
const ai = err instanceof AIError ? err : null;
if (!ai) app.log('error', 'Assistant turn failed', err);
emit({ type: 'error', code: ai?.code ?? 'server', message: ai?.message ?? 'The assistant stopped unexpectedly.' });
emit({ type: 'done', conversationId: id, title: '' });
})
.finally(() => {
if (id && live.get(id) === turn) live.delete(id);
});
if (!id) throw new AIError('server', 'The assistant could not start.');
return { conversationId: id };
}
const MAX_STEPS = 12;
const TOOL_OUTPUT_LIMIT = 28_000;
@ -890,10 +1038,16 @@ export async function runAssistantTurn(
input: z.input<typeof assistantRequestSchema>,
emit: (event: AssistantEvent) => void,
signal?: AbortSignal,
/** Called synchronously, before the first await, with the conversation id. */
onConversation?: (conversationId: string) => void,
): Promise<void> {
const { db } = app;
const req = assistantRequestSchema.parse(input);
const context: AssistantContext = { classId: req.context?.classId ?? null, documentIds: req.context?.documentIds };
const tags = resolveTags(db, req.context?.items);
// Tagged documents join the documents in focus so retrieval and generation use them.
const taggedDocs = tags.filter((t) => t.kind === 'document').map((t) => t.id);
const documentIds = [...new Set([...(req.context?.documentIds ?? []), ...taggedDocs])];
const context: AssistantContext = { classId: req.context?.classId ?? null, documentIds: documentIds.length ? documentIds : undefined, items: tags };
const resolved = resolveModel(app, 'chat', req.modelId);
const at = now();
@ -912,8 +1066,9 @@ export async function runAssistantTurn(
const save = (role: 'user' | 'assistant', message: ChatMessage, meta: MessageMeta = {}) =>
db.run('INSERT INTO messages (conversation_id, role, content, meta, created_at) VALUES (?, ?, ?, ?, ?)', conversationId, role, JSON.stringify(message), JSON.stringify(meta), now());
save('user', { role: 'user', content: [{ type: 'text', text: req.message }] });
save('user', { role: 'user', content: [{ type: 'text', text: req.message }] }, tags.length ? { tags } : {});
db.run('UPDATE conversations SET updated_at = ? WHERE id = ?', now(), conversationId);
onConversation?.(conversationId);
emit({ type: 'start', conversationId, model: resolved.model.label });
const env: ToolEnv = { app, conversationId, context, signal, modelId: req.modelId };