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

@ -363,7 +363,7 @@ export function getAttempt(db: DB, id: string): AttemptDto {
export const attemptPatchSchema = z.object({
answers: z
.record(z.string(), z.object({ selected: z.array(z.string().max(40)).max(12), checked: z.boolean().optional().default(false) }))
.record(z.string(), z.object({ selected: z.array(z.string().max(80)).max(12), checked: z.boolean().optional().default(false) }))
.optional(),
flags: z.array(z.string()).max(1000).optional(),
currentIndex: z.number().int().min(0).optional(),
@ -390,7 +390,8 @@ export function patchAttempt(db: DB, id: string, input: z.input<typeof attemptPa
// A checked practice answer is final: feedback has been shown.
if (prev?.checked && row.mode === 'practice') continue;
const valid = new Set(q.options.map((o) => o.id));
const selected = [...new Set(a.selected.filter((s) => valid.has(s)))];
// Numeric questions store what was typed; choice questions store option ids.
const selected = q.type === 'numeric' ? a.selected.slice(0, 1).map((s) => s.trim().slice(0, 60)).filter(Boolean) : [...new Set(a.selected.filter((s) => valid.has(s)))];
const checked = row.mode === 'practice' && a.checked && selected.length > 0;
answers[qid] = { selected, checked, at };
if (checked) recordResponse(db, row, q, selected, settings.sataScoring, at);

View file

@ -11,6 +11,7 @@
* ("why do patients on furosemide need bananas?") also find the right passage.
*/
import { z } from 'zod';
import { LOCAL_EMBEDDING_LABEL, LOCAL_EMBEDDING_MODEL, LOCAL_PROVIDER_ID, localEmbed, localModelStatus } from '../ai/localEmbed.ts';
import { getAdapter } from '../ai/providers/index.ts';
import { providerConfigById } from '../ai/service.ts';
import { AIError, type ProviderKind } from '../ai/types.ts';
@ -23,6 +24,7 @@ import { chunkById, searchChunks, type ChunkHit, type ChunkScope } from './docum
/* ------------------------------ settings ------------------------------ */
export interface EmbeddingSettings {
/** A provider id, `local` for the built-in model, or null for keyword search only. */
providerId: string | null;
model: string;
/** Requested vector size for models that support shortening (OpenAI v3, Gemini). Null = native. */
@ -31,6 +33,13 @@ export interface EmbeddingSettings {
const SETTINGS_KEY = 'embeddings';
const EMPTY: EmbeddingSettings = { providerId: null, model: '', dimensions: null };
const LOCAL: EmbeddingSettings = { providerId: LOCAL_PROVIDER_ID, model: LOCAL_EMBEDDING_MODEL, dimensions: null };
/** Whether an install that never chose an embedding provider uses the built-in model. */
let localDefault = false;
export function setLocalEmbeddingDefault(on: boolean): void {
localDefault = on;
}
/** Suggested embedding model per provider type. Anthropic has no embeddings API. */
export const DEFAULT_EMBEDDING_MODELS: Record<ProviderKind, string | null> = {
@ -39,6 +48,7 @@ export const DEFAULT_EMBEDDING_MODELS: Record<ProviderKind, string | null> = {
ollama: 'nomic-embed-text',
openai_compatible: '',
anthropic: null,
deepseek: null,
};
/** USD per million input tokens, for the usage log. */
@ -56,7 +66,11 @@ export const embeddingSettingsSchema = z.object({
});
export function getEmbeddingSettings(db: DB): EmbeddingSettings {
return { ...EMPTY, ...getSetting<Partial<EmbeddingSettings>>(db, SETTINGS_KEY, EMPTY) };
const stored = getSetting<Partial<EmbeddingSettings> | null>(db, SETTINGS_KEY, null);
// Nothing chosen yet: the built-in model, so semantic search works without a cloud account.
if (!stored) return localDefault ? { ...LOCAL } : { ...EMPTY };
const s = { ...EMPTY, ...stored };
return s.providerId === LOCAL_PROVIDER_ID ? { ...LOCAL } : s;
}
const modelKey = (s: EmbeddingSettings) => `${s.providerId}:${s.model}:${s.dimensions ?? 'native'}`;
@ -64,7 +78,10 @@ const isConfigured = (s: EmbeddingSettings) => Boolean(s.providerId && s.model);
export function saveEmbeddingSettings(app: AppContext, input: z.input<typeof embeddingSettingsSchema>): EmbeddingSettings {
const next = embeddingSettingsSchema.parse(input);
if (next.providerId) {
if (next.providerId === LOCAL_PROVIDER_ID) {
next.model = LOCAL_EMBEDDING_MODEL;
next.dimensions = null;
} else if (next.providerId) {
const { kind } = providerConfigById(app, next.providerId);
if (!getAdapter(kind).embed) throw badRequest('This provider has no embeddings API. Choose OpenAI, Gemini, Ollama or an OpenAI-compatible server.');
if (!next.model) throw badRequest('Enter the embedding model to use.');
@ -99,6 +116,11 @@ function normalise(v: number[]): Float32Array {
export async function embedTexts(app: AppContext, texts: string[], purpose: 'document' | 'query', signal?: AbortSignal): Promise<Float32Array[]> {
const s = getEmbeddingSettings(app.db);
if (!isConfigured(s)) throw new AIError('not_configured', 'Semantic search is not set up. Choose an embedding model in Settings → AI.');
if (s.providerId === LOCAL_PROVIDER_ID) {
// Free and on this machine: nothing to log in the usage table.
const vectors = await localEmbed(app.config.dataDir, texts, purpose, signal);
return vectors.map(normalise);
}
const { cfg, kind, name } = providerConfigById(app, s.providerId!);
const adapter = getAdapter(kind);
if (!adapter.embed) throw new AIError('unsupported', `${name} has no embeddings API.`);
@ -202,7 +224,16 @@ export function embeddingStatus(app: AppContext) {
const s = getEmbeddingSettings(app.db);
const total = app.db.get<{ n: number }>('SELECT COUNT(*) AS n FROM chunks')?.n ?? 0;
const indexed = isConfigured(s) ? (app.db.get<{ n: number }>('SELECT COUNT(*) AS n FROM chunk_vectors WHERE model_key = ?', modelKey(s))?.n ?? 0) : 0;
return { settings: s, configured: isConfigured(s), indexed, total, running: state.running, lastError: state.lastError, defaults: DEFAULT_EMBEDDING_MODELS };
return {
settings: s,
configured: isConfigured(s),
indexed,
total,
running: state.running,
lastError: state.lastError,
defaults: DEFAULT_EMBEDDING_MODELS,
local: { ...localModelStatus(app.config.dataDir), label: LOCAL_EMBEDDING_LABEL, enabledByDefault: localDefault },
};
}
/* ------------------------------ vector search ------------------------------ */

View file

@ -2,7 +2,8 @@
* Reusable templates.
* - quiz / deck: a content skeleton (or a full copy of an existing item) to start from.
* - generation: a saved set of AI generation options.
* Built-in templates are (re)seeded at startup and cannot be edited, only copied.
* Built-in templates are (re)seeded at startup. They can be edited: an edited built-in is
* stored with builtin = 2, which seeding leaves alone, and "reset" restores the original.
*/
import { z } from 'zod';
import type { DB } from '../db.ts';
@ -33,7 +34,9 @@ const mapTemplate = (r: TemplateRow) => ({
name: r.name,
description: r.description,
payload: parseJson<Record<string, unknown>>(r.payload, {}),
builtin: Boolean(r.builtin),
builtin: r.builtin > 0,
/** A built-in template the user has changed. */
edited: r.builtin === 2,
updatedAt: r.updated_at,
});
@ -177,11 +180,12 @@ export function seedTemplates(db: DB): void {
const at = now();
db.tx(() => {
const keep = BUILTIN.map((t) => t.id);
db.run(`DELETE FROM templates WHERE builtin = 1 AND id NOT IN (${keep.map(() => '?').join(',')})`, ...keep);
db.run(`DELETE FROM templates WHERE builtin > 0 AND id NOT IN (${keep.map(() => '?').join(',')})`, ...keep);
for (const t of BUILTIN) {
db.run(
`INSERT INTO templates (id, kind, name, description, payload, builtin, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 1, ?, ?)
ON CONFLICT(id) DO UPDATE SET kind = excluded.kind, name = excluded.name, description = excluded.description, payload = excluded.payload, updated_at = excluded.updated_at`,
ON CONFLICT(id) DO UPDATE SET kind = excluded.kind, name = excluded.name, description = excluded.description, payload = excluded.payload, updated_at = excluded.updated_at
WHERE templates.builtin = 1`,
t.id,
t.kind,
t.name,
@ -210,19 +214,28 @@ export function createTemplate(db: DB, input: z.input<typeof templateInputSchema
}
export function updateTemplate(db: DB, id: string, input: { name?: string; description?: string; payload?: Record<string, unknown> }) {
const row = db.get<TemplateRow>('SELECT * FROM templates WHERE id = ? AND builtin = 0', id);
const row = db.get<TemplateRow>('SELECT * FROM templates WHERE id = ?', id);
if (!row) throw notFound('Template');
db.run(
'UPDATE templates SET name = ?, description = ?, payload = ?, updated_at = ? WHERE id = ?',
'UPDATE templates SET name = ?, description = ?, payload = ?, builtin = ?, updated_at = ? WHERE id = ?',
input.name?.trim().slice(0, 120) || row.name,
input.description ?? row.description,
input.payload ? JSON.stringify(input.payload) : row.payload,
row.builtin > 0 ? 2 : 0,
now(),
id,
);
return mapTemplate(db.get<TemplateRow>('SELECT * FROM templates WHERE id = ?', id)!);
}
/** Puts an edited built-in template back to how it shipped. */
export function resetTemplate(db: DB, id: string) {
const original = BUILTIN.find((t) => t.id === id);
if (!original) throw notFound('Template');
db.run('UPDATE templates SET name = ?, description = ?, payload = ?, builtin = 1, updated_at = ? WHERE id = ?', original.name, original.description, JSON.stringify(original.payload), now(), id);
return mapTemplate(db.get<TemplateRow>('SELECT * FROM templates WHERE id = ?', id)!);
}
export function deleteTemplate(db: DB, id: string): void {
const { changes } = db.run('DELETE FROM templates WHERE id = ? AND builtin = 0', id);
if (!changes) throw notFound('Template');