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

@ -0,0 +1,338 @@
import { useQuery } from '@tanstack/react-query';
import { BookOpen, Bot, ChevronRight, Layers, MessageSquareText, NotebookPen, Pencil, RotateCcw, Trash2 } from 'lucide-react';
import { useEffect, useState, type ReactNode } from 'react';
import { toast } from 'sonner';
import { api, errorMessage } from '@/lib/api';
import { qk, useRefresh } from '@/lib/queries';
import type { Template } from '@/lib/types';
import { cx, plural } from '@/lib/util';
import { Badge, Button, Dialog, Field, IconButton, Input, Section, Segmented, Select, Skeleton, Textarea, useConfirm } from '@/ui';
/* ------------------------------ shared text editor ------------------------------ */
/** A collapsible row holding one block of instructions, with save and reset. */
function InstructionRow({ label, text, builtin, customized, onSave }: { label: string; text: string; builtin: string; customized: boolean; onSave: (text: string | null) => Promise<void> }) {
const [open, setOpen] = useState(false);
const [value, setValue] = useState(text);
const [busy, setBusy] = useState(false);
useEffect(() => setValue(text), [text]);
const dirty = value.trim() !== text.trim();
const save = async (next: string | null) => {
setBusy(true);
try {
await onSave(next);
toast.success(next === null ? 'Back to the built-in wording' : 'Saved');
} catch (e) {
toast.error(errorMessage(e));
} finally {
setBusy(false);
}
};
return (
<li>
<button type="button" aria-expanded={open} onClick={() => setOpen(!open)} className="flex w-full items-center gap-2.5 px-4 py-3 text-left hover:bg-ink/4">
<ChevronRight className={cx('size-4 shrink-0 text-ink-3 transition-transform', open && 'rotate-90')} />
<span className="min-w-0 flex-1 truncate text-sm font-medium">{label}</span>
{customized ? <Badge tone="accent">Edited</Badge> : <Badge>Built in</Badge>}
</button>
{open && (
<div className="px-4 pb-4">
<Textarea value={value} onChange={(e) => setValue(e.target.value)} rows={12} spellCheck={false} aria-label={label} className="num text-[12.5px] leading-relaxed" />
<div className="mt-2 flex flex-wrap items-center gap-2">
<Button size="sm" variant="primary" disabled={!dirty || value.trim().length < 10} loading={busy} onClick={() => save(value)}>
Save
</Button>
{dirty && (
<Button size="sm" variant="ghost" onClick={() => setValue(text)}>
Undo changes
</Button>
)}
{(customized || value.trim() !== builtin.trim()) && (
<Button size="sm" variant="ghost" icon={<RotateCcw />} className="ml-auto" disabled={busy} onClick={() => save(null)}>
Reset to built-in
</Button>
)}
</div>
</div>
)}
</li>
);
}
/* ------------------------------ import (outside chatbot) instructions ------------------------------ */
interface LlmInstructions {
quiz: string;
deck: string;
customized: { quiz: boolean; deck: boolean };
builtin?: { quiz: string; deck: string };
}
function ImportInstructions() {
const q = useQuery({ queryKey: ['llm-instructions'], queryFn: () => api.get<LlmInstructions>('/api/llm-instructions') });
if (!q.data) return <Skeleton className="h-28" />;
const save = (kind: 'quiz' | 'deck') => async (text: string | null) => {
await api.put('/api/llm-instructions', { kind, text });
await q.refetch();
};
return (
<Section title="Import instructions (manual generation)">
<ul className="card divide-y divide-line overflow-hidden">
<InstructionRow label="Quiz questions" text={q.data.quiz} builtin={q.data.builtin?.quiz ?? q.data.quiz} customized={q.data.customized.quiz} onSave={save('quiz')} />
<InstructionRow label="Flashcards" text={q.data.deck} builtin={q.data.builtin?.deck ?? q.data.deck} customized={q.data.customized.deck} onSave={save('deck')} />
</ul>
<p className="mt-2 text-xs text-ink-3">
What "AI instructions" in the Import window copies for ChatGPT, Claude or another chatbot you use yourself. They describe the import JSON format, so keep that part intact.
</p>
</Section>
);
}
/* ------------------------------ built-in generator instructions ------------------------------ */
interface GenerationInstruction {
key: string;
group: string;
label: string;
text: string;
builtin: string;
customized: boolean;
}
function GeneratorInstructions() {
const q = useQuery({ queryKey: ['ai', 'instructions'], queryFn: () => api.get<{ instructions: GenerationInstruction[] }>('/api/ai/instructions').then((r) => r.instructions) });
if (!q.data) return <Skeleton className="h-40" />;
const groups = [...new Set(q.data.map((i) => i.group))];
const save = (key: string) => async (text: string | null) => {
await api.put('/api/ai/instructions', { key, text });
await q.refetch();
};
return (
<Section title="AI generation instructions (automatic generation)">
<div className="space-y-3">
{groups.map((g) => (
<div key={g}>
<div className="mb-1.5 text-xs font-medium text-ink-3">{g}</div>
<ul className="card divide-y divide-line overflow-hidden">
{q.data!
.filter((i) => i.group === g)
.map((i) => (
<InstructionRow key={i.key} label={i.label} text={i.text} builtin={i.builtin} customized={i.customized} onSave={save(i.key)} />
))}
</ul>
</div>
))}
</div>
<p className="mt-2 text-xs text-ink-3">
Sent to your connected AI model when you use Generate or ask the assistant to make quizzes, flashcards or study guides. The output format is handled separately, so these only need to
describe what good material looks like.
</p>
</Section>
);
}
/* ------------------------------ generation presets ------------------------------ */
type PresetKind = 'quiz' | 'deck' | 'note';
function PresetDialog({ template, onClose }: { template: Template | null; onClose: () => void }) {
const refresh = useRefresh();
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [payload, setPayload] = useState<Record<string, any>>({});
const [busy, setBusy] = useState(false);
useEffect(() => {
if (!template) return;
setName(template.name);
setDescription(template.description);
setPayload({ ...template.payload });
}, [template]);
const set = (patch: Record<string, unknown>) => setPayload((p) => ({ ...p, ...patch }));
const kind: PresetKind = payload.kind ?? 'quiz';
const save = async () => {
if (!template) return;
setBusy(true);
try {
const clean = { ...payload };
if (kind !== 'quiz') ['style', 'difficulty', 'sataShare'].forEach((k) => delete clean[k]);
if (kind !== 'deck') delete clean.cardStyle;
if (kind !== 'note') delete clean.noteStyle;
if (kind === 'note') delete clean.count;
if (!String(clean.instructions ?? '').trim()) delete clean.instructions;
await api.patch(`/api/templates/${template.id}`, { name, description, payload: clean });
await refresh();
toast.success('Preset saved');
onClose();
} catch (e) {
toast.error(errorMessage(e));
} finally {
setBusy(false);
}
};
return (
<Dialog
open={template !== null}
onOpenChange={(o) => !o && onClose()}
title="Edit preset"
description={template?.builtin ? 'A built-in preset. Your changes are kept, and you can reset it later.' : undefined}
footer={
<>
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button variant="primary" loading={busy} disabled={!name.trim()} onClick={save}>
Save
</Button>
</>
}
>
<div className="space-y-4">
<Field label="Name">
<Input value={name} onChange={(e) => setName(e.target.value)} maxLength={120} />
</Field>
<Field label="Description" optional>
<Input value={description} onChange={(e) => setDescription(e.target.value)} maxLength={1000} />
</Field>
<Segmented<PresetKind>
label="Creates"
value={kind}
onChange={(k) => set({ kind: k })}
options={[
{ value: 'quiz', label: 'Quiz', icon: <BookOpen /> },
{ value: 'deck', label: 'Flashcards', icon: <Layers /> },
{ value: 'note', label: 'Study guide', icon: <NotebookPen /> },
]}
/>
{kind !== 'note' && (
<Field label={kind === 'quiz' ? 'Questions' : 'Cards'}>
<Input type="number" min={1} max={200} value={payload.count ?? (kind === 'quiz' ? 15 : 30)} onChange={(e) => set({ count: Math.max(1, Math.min(200, Number(e.target.value) || 1)) })} className="w-28" />
</Field>
)}
{kind === 'quiz' && (
<div className="grid gap-3 sm:grid-cols-3">
<Field label="Style">
<Select value={payload.style ?? 'nclex'} onChange={(e) => set({ style: e.target.value })}>
<option value="nclex">NCLEX</option>
<option value="standard">Standard</option>
<option value="recall">Quick recall</option>
</Select>
</Field>
<Field label="Difficulty">
<Select value={payload.difficulty ?? 'mixed'} onChange={(e) => set({ difficulty: e.target.value })}>
<option value="mixed">Mixed</option>
<option value="easy">Easy</option>
<option value="medium">Medium</option>
<option value="hard">Hard</option>
</Select>
</Field>
<Field label={`Select all: ${Math.round((payload.sataShare ?? 0.3) * 100)}%`}>
<input type="range" min={0} max={100} step={5} value={Math.round((payload.sataShare ?? 0.3) * 100)} onChange={(e) => set({ sataShare: Number(e.target.value) / 100 })} className="mt-3 w-full accent-[var(--accent)]" />
</Field>
</div>
)}
{kind === 'deck' && (
<Field label="Card style">
<Select value={payload.cardStyle ?? 'concise'} onChange={(e) => set({ cardStyle: e.target.value })}>
<option value="concise">Concise</option>
<option value="detailed">Detailed</option>
<option value="medication">Medication</option>
<option value="definition">Term and definition</option>
</Select>
</Field>
)}
{kind === 'note' && (
<Field label="Guide style">
<Select value={payload.noteStyle ?? 'study_guide'} onChange={(e) => set({ noteStyle: e.target.value })}>
<option value="study_guide">Study guide</option>
<option value="summary">Summary</option>
<option value="outline">Outline</option>
<option value="cheat_sheet">Cheat sheet</option>
</Select>
</Field>
)}
<Field label="Extra instructions" optional hint="Added to the AI generation instructions whenever this preset is used.">
<Textarea rows={4} value={payload.instructions ?? ''} onChange={(e) => set({ instructions: e.target.value })} />
</Field>
</div>
</Dialog>
);
}
/* ------------------------------ page ------------------------------ */
export function TemplateSettings() {
const refresh = useRefresh();
const confirm = useConfirm();
const [editing, setEditing] = useState<Template | null>(null);
const q = useQuery({ queryKey: qk.templates, queryFn: () => api.get<{ templates: Template[] }>('/api/templates').then((r) => r.templates) });
if (!q.data) return <Skeleton className="h-48" />;
const groups: { kind: Template['kind']; title: string; blurb: string; icon: ReactNode }[] = [
{ kind: 'generation', title: 'AI generation presets', blurb: 'Appear under "Preset" when you generate with AI. Built-in presets can be edited and reset.', icon: <Bot /> },
{ kind: 'quiz', title: 'Quiz templates', blurb: 'Appear under "Start from" when you create a quiz. Save any quiz as a template from its menu.', icon: <BookOpen /> },
{ kind: 'deck', title: 'Flashcard templates', blurb: 'Appear under "Start from" when you create a deck.', icon: <Layers /> },
];
const act = async (fn: () => Promise<unknown>, message: string) => {
try {
await fn();
await refresh();
toast.success(message);
} catch (e) {
toast.error(errorMessage(e));
}
};
return (
<>
<GeneratorInstructions />
<ImportInstructions />
{groups.map((g) => {
const list = q.data!.filter((t) => t.kind === g.kind);
return (
<Section key={g.kind} title={g.title}>
<ul className="card divide-y divide-line">
{list.map((t) => (
<li key={t.id} className="flex items-center gap-3 px-4 py-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="truncate text-sm font-medium">{t.name}</span>
{t.edited ? <Badge tone="accent">Edited</Badge> : t.builtin ? <Badge>Built in</Badge> : <Badge tone="accent">Yours</Badge>}
</div>
{t.description && <div className="mt-0.5 line-clamp-2 text-[13px] text-ink-2">{t.description}</div>}
{t.kind !== 'generation' && <div className="mt-0.5 text-xs text-ink-3">{t.kind === 'quiz' ? plural((t.payload.questions ?? []).length, 'question') : plural((t.payload.cards ?? []).length, 'card')}</div>}
</div>
{t.kind === 'generation' && (
<IconButton label="Edit preset" size="sm" onClick={() => setEditing(t)}>
<Pencil />
</IconButton>
)}
{t.edited && (
<IconButton label="Reset to built-in" size="sm" onClick={() => act(() => api.post(`/api/templates/${t.id}/reset`), 'Preset reset')}>
<RotateCcw />
</IconButton>
)}
{!t.builtin && (
<IconButton
label="Delete template"
size="sm"
onClick={async () => {
if (!(await confirm({ title: 'Delete this template?', message: `"${t.name}" will be removed.`, confirmLabel: 'Delete', danger: true }))) return;
await act(() => api.del(`/api/templates/${t.id}`), 'Template deleted');
}}
>
<Trash2 />
</IconButton>
)}
</li>
))}
{list.length === 0 && <li className="px-4 py-4 text-[13px] text-ink-3">None yet.</li>}
</ul>
<p className="mt-2 flex items-center gap-1.5 text-xs text-ink-3">{g.blurb}</p>
</Section>
);
})}
<p className="flex items-center gap-1.5 text-xs text-ink-3">
<MessageSquareText className="size-3.5" /> Changes apply to new generations. Drafts that are already written are not affected.
</p>
<PresetDialog template={editing} onClose={() => setEditing(null)} />
</>
);
}