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

@ -32,5 +32,9 @@
# Number of automatic daily database snapshots to keep. # Number of automatic daily database snapshots to keep.
# BACKUP_KEEP=7 # BACKUP_KEEP=7
# Use the built-in embedding model for semantic search until another is chosen (default on).
# The model (~35 MB) is downloaded once into DATA_DIR/models.
# LOCAL_EMBEDDINGS=on
# Timezone used for "today", streaks and due dates until you change it in Settings. # Timezone used for "today", streaks and due dates until you change it in Settings.
# TZ=America/Phoenix # TZ=America/Phoenix

View file

@ -11,7 +11,11 @@ FROM deps AS test
RUN npm run typecheck && npm test RUN npm run typecheck && npm test
FROM deps AS build FROM deps AS build
RUN npm run build && npm prune --omit=dev # ONNX Runtime (built-in embedding model) ships binaries for every OS and CPU; keep only this one.
RUN npm run build && npm prune --omit=dev \
&& ARCH="$(node -p process.arch)" \
&& find node_modules/onnxruntime-node/bin -mindepth 2 -maxdepth 2 -type d ! -name linux -exec rm -rf {} + \
&& find node_modules/onnxruntime-node/bin -mindepth 3 -maxdepth 3 -type d ! -name "$ARCH" -exec rm -rf {} +
FROM node:24-bookworm-slim AS runtime FROM node:24-bookworm-slim AS runtime
ENV NODE_ENV=production HOST=0.0.0.0 PORT=3726 DATA_DIR=/data WEB_DIR=/app/dist/web ENV NODE_ENV=production HOST=0.0.0.0 PORT=3726 DATA_DIR=/data WEB_DIR=/app/dist/web

View file

@ -61,10 +61,34 @@ type-grouped materials, copyable import instructions and assistant library links
enabled from Settings and indexed; a 1-minute exam counted down on the wall clock and enabled from Settings and indexed; a 1-minute exam counted down on the wall clock and
auto-submitted at 60 s; a shared session kept original questions after the owner edited them. auto-submitted at 60 s; a shared session kept original questions after the owner edited them.
## 2026-11-15: first revision (owner's 21-item list)
Implemented and verified on an isolated instance (`.test-data/rev1`, port 3743):
DeepSeek provider (`server/ai/providers/deepseek.ts`); 7 reasoning-effort levels mapped per
adapter; the "does not support tool calling" errors were DeepSeek rejecting forced tool choice
in thinking mode: compatible servers now get the call requested in the prompt, and only a
genuine "no tools" 400 reports unsupported. Cached-input prices (migration 3) and cache-write
/off-peak aware costs. Built-in embeddings (`server/ai/localEmbed.ts`, bge-small, default when
nothing is chosen). Assistant turns run server-side independent of the browser (re-attach via
`GET /api/ai/chat/:id/stream`, stop via `POST /api/ai/chat/:id/stop`); drafts tray in the
sidebar/Today. Quiz start screen, navigator ring/legend fix, timer only for timed exams,
7-point letter grades, numeric questions (migration 3 rebuilds `questions` for the new type;
answers are compared numerically, units ignored, optional ± tolerance). Dialog footer padding
(`safe-pb-3`), keyboard hints removed, small assistant button, full-width assistant page, model
switcher and @-tagging. Editable generator instructions and built-in presets (builtin = 2 marks
an edited built-in), separate chatbot import instructions. Copy buttons work over plain HTTP
inside dialogs. Class/folder shares include processed documents.
Live DeepSeek (`deepseek-flash` only) checks passed: discovery, quiz generation at default and
Max effort (numeric items produced, answer keys correct with thinking on), multi-step tool
turns, follow-up turns, tagged quiz to flashcards, an answer finishing after disconnect; zero
errors in Usage. Docker image builds; ONNX Runtime and the embedding model run in the container.
The image grew to about 1.3 GB because of ONNX Runtime.
## Verification status ## Verification status
Baseline: 162 tests passed, TypeScript passed and production web/server builds passed. Baseline: 162 tests passed, TypeScript passed and production web/server builds passed.
Added six regression tests. Full `npm run check` passes: **181 tests** (2026-11-12), TypeScript Added six regression tests. Full `npm run check` passes: **208 tests** (2026-11-15; 181 on 2026-11-12), TypeScript
and both production builds. The Docker `test` stage runs the same 181 tests on Node 24. Tests were run with loopback access for the mock provider. and both production builds. The Docker `test` stage runs the same 181 tests on Node 24. Tests were run with loopback access for the mock provider.
The earlier agent manually exercised quiz completion/results, flashcards, streak effects, The earlier agent manually exercised quiz completion/results, flashcards, streak effects,
@ -83,7 +107,7 @@ full offline administrator study is not implemented.
2. With owner-supplied provider connections: verify live discovery, streamed chat, generation, 2. With owner-supplied provider connections: verify live discovery, streamed chat, generation,
OCR and task routing. No real-provider calls should be inferred from mock test results. OCR and task routing. No real-provider calls should be inferred from mock test results.
3. Future optional work: approved ChatGPT account OAuth, more robust offline studying and 3. Future optional work: approved ChatGPT account OAuth, more robust offline studying and
semantic embeddings (current retrieval is lexical FTS5). (semantic embeddings were added on 2026-11-12, the built-in model on 2026-11-15).
## Resume safely ## Resume safely

View file

@ -33,19 +33,24 @@ is an opt-in development tool, never part of startup.
## What is implemented ## What is implemented
- Classes, folders, search, edit/duplicate/move/delete actions; Markdown and embedded images. - Classes, folders, search, edit/duplicate/move/delete actions; Markdown and embedded images.
- Multiple-choice and select-all quizzes; practice feedback, exam timers, shuffle, partial - Multiple-choice, select-all and numeric (type-the-answer calculation) questions; a start
credit, saved sessions, missed-question review, results and history. screen that hides answers, practice feedback, optional exam time limits, shuffle, partial
credit, saved sessions, missed-question review, 7-point letter grades and history.
- Flashcard editing, browse/self-assessment sessions, FSRS scheduling, persistent reviews, - Flashcard editing, browse/self-assessment sessions, FSRS scheduling, persistent reviews,
undo, keyboard shortcuts and streak effects. undo, keyboard shortcuts and streak effects.
- Public quiz/deck/class/folder/note links and explicitly shared documents. Collection shares - Public quiz/deck/class/folder/note/document links. Collection (class and folder) shares
include current and future quizzes, decks and notes; uploaded documents stay private. include current and future quizzes, decks, notes and processed documents.
- JSON import previews, validation, templates, content exports and a V1 SQLite import path. - JSON import previews, validation, templates, content exports and a V1 SQLite import path.
- PDF/DOCX/PPTX/TXT/Markdown/image uploads; text extraction, OCR via a configured vision model, - PDF/DOCX/PPTX/TXT/Markdown/image uploads; text extraction, OCR via a configured vision model,
chunking and SQLite FTS retrieval with source references. chunking and SQLite FTS retrieval with source references.
- OpenAI, Anthropic, Gemini, OpenAI-compatible and Ollama provider connections, manual/discovered - OpenAI, Anthropic, Gemini, DeepSeek, OpenAI-compatible and Ollama provider connections,
models, task routing, encrypted keys and usage estimates. manual/discovered models, task routing with reasoning effort from Off to Max, encrypted keys
- AI generation with editable drafts; an assistant that searches materials, reads notes, and usage estimates that price cached input separately.
creates drafts, finds weak topics and proposes confirmed content changes. - Semantic search with cloud embeddings or a built-in model that runs on the server.
- AI generation with editable drafts and editable instructions/presets; generation and
assistant answers keep running on the server when you leave the page. The assistant
searches materials, reads notes, creates drafts, finds weak topics, proposes confirmed
content changes, accepts @-tagged materials and can switch models per chat.
- Responsive light/dark interface and an installable app shell. Offline studying is limited: - Responsive light/dark interface and an installable app shell. Offline studying is limited:
private data is not cached; most operations need a server connection. private data is not cached; most operations need a server connection.

View file

@ -5,8 +5,20 @@ discover models where supported (or add a custom model), enable models and selec
for generation, chat, explanations and vision. Output limits, capabilities, pricing and for generation, chat, explanations and vision. Output limits, capabilities, pricing and
reasoning settings can be edited per model. Catalog prices are estimates, not billing records. reasoning settings can be edited per model. Catalog prices are estimates, not billing records.
Adapters use OpenAI Responses, Anthropic Messages, Gemini generateContent, OpenAI-compatible Adapters use OpenAI Responses, Anthropic Messages, Gemini generateContent, DeepSeek and
Chat Completions and Ollama's native chat API. Configure the endpoint as shown in Settings. OpenAI-compatible Chat Completions, and Ollama's native chat API.
Reasoning effort has seven levels (Off, Minimal, Low, Medium, High, Extra high, Max); each
adapter maps them onto the nearest value its API accepts. DeepSeek accepts low / high / max
and turns thinking off at "Off". DeepSeek rejects forced tool calls in thinking mode, so
structured generation keeps thinking on and asks for the tool call in the prompt; answer keys
were noticeably less reliable with thinking off. Its `reasoning_content` is replayed between
tool steps, as the API requires.
Cost estimates split input into fresh, cache-hit and cache-write tokens. A model's "Cached
input price" is used when set; otherwise the provider's published discount applies (10% of
input for GPT-5+, Claude and Gemini; DeepSeek's catalog cache-hit price). DeepSeek's
off-peak half price is applied by time of call. Configure the endpoint as shown in Settings.
Local models are reached **from the server/container**: `localhost` inside Docker is the Local models are reached **from the server/container**: `localhost` inside Docker is the
container itself, not your workstation or Unraid host. Use a reachable LAN address instead. container itself, not your workstation or Unraid host. Use a reachable LAN address instead.
@ -31,7 +43,10 @@ warning on the document. At most 600 pages are read per file.
Settings → AI → Semantic search chooses an embeddings provider and model (suggested: Settings → AI → Semantic search chooses an embeddings provider and model (suggested:
OpenAI `text-embedding-3-small`, Gemini `gemini-embedding-001`, Ollama `nomic-embed-text`; OpenAI `text-embedding-3-small`, Gemini `gemini-embedding-001`, Ollama `nomic-embed-text`;
Anthropic has no embeddings API). Every document passage is embedded in the background and Anthropic and DeepSeek have no embeddings API). Until something else is chosen, the built-in
model is used: BAAI bge-small-en-v1.5 (8-bit ONNX, 384 dimensions) running on the server's CPU
through transformers.js. It is downloaded once (about 35 MB) from huggingface.co into
`DATA_DIR/models` on first use and costs nothing. `LOCAL_EMBEDDINGS=off` disables the default. Every document passage is embedded in the background and
stored as a vector in SQLite (`chunk_vectors`). Search, the assistant's document search and stored as a vector in SQLite (`chunk_vectors`). Search, the assistant's document search and
focused generation then merge keyword (FTS5) and meaning-based rankings with reciprocal-rank focused generation then merge keyword (FTS5) and meaning-based rankings with reciprocal-rank
fusion, so exact terms still match while paraphrased questions find the right passage. If the fusion, so exact terms still match while paraphrased questions find the right passage. If the

977
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -25,6 +25,7 @@
"@fontsource-variable/jetbrains-mono": "^5.3.0", "@fontsource-variable/jetbrains-mono": "^5.3.0",
"@fontsource-variable/newsreader": "^5.3.0", "@fontsource-variable/newsreader": "^5.3.0",
"@hono/node-server": "^2.1.6", "@hono/node-server": "^2.1.6",
"@huggingface/transformers": "^4.3.2",
"@tanstack/react-query": "^5.107.1", "@tanstack/react-query": "^5.107.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"fast-xml-parser": "^5.12.0", "fast-xml-parser": "^5.12.0",

View file

@ -11,7 +11,7 @@ import { z } from 'zod';
import type { DraftCard, DraftQuestion } from '../../shared/content.ts'; import type { DraftCard, DraftQuestion } from '../../shared/content.ts';
import { draftsFromValue } from '../../shared/importer.ts'; import { draftsFromValue } from '../../shared/importer.ts';
import type { DB } from '../db.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 { getAppSettings } from '../settings.ts';
import { createAttempt, missedQuestionIds } from '../services/attempts.ts'; import { createAttempt, missedQuestionIds } from '../services/attempts.ts';
import { createClass, createFolder, getClass, getDeck, getQuiz, listCards, listQuestions, resolveFolder } from '../services/content.ts'; import { createClass, createFolder, getClass, getDeck, getQuiz, listCards, listQuestions, resolveFolder } from '../services/content.ts';
@ -52,6 +52,16 @@ export type AssistantEvent =
export interface AssistantContext { export interface AssistantContext {
classId?: string | null; classId?: string | null;
documentIds?: string[]; 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 { interface ToolRun {
@ -483,7 +493,7 @@ const TOOLS: ToolSpec[] = [
type: 'array', type: 'array',
items: obj( 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, stem: S,
options: { type: 'array', items: obj({ text: S, correct: { type: 'boolean' }, why: S }, ['text', 'correct']) }, options: { type: 'array', items: obj({ text: S, correct: { type: 'boolean' }, why: S }, ['text', 'correct']) },
rationale: S, rationale: S,
@ -744,6 +754,8 @@ interface MessageRow {
interface MessageMeta { interface MessageMeta {
hidden?: boolean; hidden?: boolean;
toolResults?: boolean; toolResults?: boolean;
/** Materials tagged in a user message. */
tags?: TaggedItem[];
tools?: ToolActivity[]; tools?: ToolActivity[];
ui?: UiItem[]; ui?: UiItem[];
model?: string; model?: string;
@ -754,6 +766,7 @@ export interface DisplayMessage {
id: number; id: number;
role: 'user' | 'assistant'; role: 'user' | 'assistant';
text: string; text: string;
tags?: TaggedItem[];
tools: ToolActivity[]; tools: ToolActivity[];
ui: UiItem[]; ui: UiItem[];
model?: string; 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(''); const text = msg.content.filter((p) => p.type === 'text').map((p) => (p as { text: string }).text).join('');
if (row.role === 'user') { if (row.role === 'user') {
current = null; 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; continue;
} }
if (!current) { 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); 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 (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( lines.push(
`How to work: `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. - 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({ export const assistantRequestSchema = z.object({
conversationId: z.string().nullish(), conversationId: z.string().nullish(),
message: z.string().trim().min(1).max(20_000), 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(), 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 MAX_STEPS = 12;
const TOOL_OUTPUT_LIMIT = 28_000; const TOOL_OUTPUT_LIMIT = 28_000;
@ -890,10 +1038,16 @@ export async function runAssistantTurn(
input: z.input<typeof assistantRequestSchema>, input: z.input<typeof assistantRequestSchema>,
emit: (event: AssistantEvent) => void, emit: (event: AssistantEvent) => void,
signal?: AbortSignal, signal?: AbortSignal,
/** Called synchronously, before the first await, with the conversation id. */
onConversation?: (conversationId: string) => void,
): Promise<void> { ): Promise<void> {
const { db } = app; const { db } = app;
const req = assistantRequestSchema.parse(input); 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 resolved = resolveModel(app, 'chat', req.modelId);
const at = now(); const at = now();
@ -912,8 +1066,9 @@ export async function runAssistantTurn(
const save = (role: 'user' | 'assistant', message: ChatMessage, meta: MessageMeta = {}) => 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()); 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); db.run('UPDATE conversations SET updated_at = ? WHERE id = ?', now(), conversationId);
onConversation?.(conversationId);
emit({ type: 'start', conversationId, model: resolved.model.label }); emit({ type: 'start', conversationId, model: resolved.model.label });
const env: ToolEnv = { app, conversationId, context, signal, modelId: req.modelId }; const env: ToolEnv = { app, conversationId, context, signal, modelId: req.modelId };

View file

@ -39,6 +39,7 @@ import {
import { chunkById, formatExcerpts, searchChunks, selectContext, sourceLabel, type ChunkHit } from '../services/documents.ts'; import { chunkById, formatExcerpts, searchChunks, selectContext, sourceLabel, type ChunkHit } from '../services/documents.ts';
import { hybridSearch } from '../services/semantic.ts'; import { hybridSearch } from '../services/semantic.ts';
import { weakTopics } from '../services/stats.ts'; import { weakTopics } from '../services/stats.ts';
import { getSetting, setSetting } from '../settings.ts';
import { newId, now, parseJson } from '../util.ts'; import { newId, now, parseJson } from '../util.ts';
import { generateStructured, resolveModel, runChat } from './service.ts'; import { generateStructured, resolveModel, runChat } from './service.ts';
import { AIError } from './types.ts'; import { AIError } from './types.ts';
@ -297,10 +298,15 @@ const QUESTION_SCHEMA = {
items: { items: {
type: 'object', type: 'object',
properties: { properties: {
type: { type: 'string', enum: ['single', 'multi'], description: 'single = one correct answer; multi = select all that apply' }, type: {
type: 'string',
enum: ['single', 'multi', 'numeric'],
description: 'single = one correct answer; multi = select all that apply; numeric = a calculation the student answers by typing the number',
},
stem: { type: 'string', description: 'The question. Markdown allowed.' }, stem: { type: 'string', description: 'The question. Markdown allowed.' },
options: { options: {
type: 'array', type: 'array',
description: 'Answer choices. For numeric questions: exactly one option, the correct answer with its unit (e.g. "12.5 mL"), correct = true, and "why" showing the calculation.',
items: { items: {
type: 'object', type: 'object',
properties: { properties: {
@ -343,6 +349,8 @@ const CARD_SCHEMA = {
required: ['cards'], required: ['cards'],
}; };
const NUMERIC_RULE = `- Calculation items (dosages, weight-based doses, IV and drip rates, conversions, intake and output) use type "numeric": the student types the number instead of choosing. Give exactly one option, the correct answer with its unit (for example "12.5 mL"), marked correct, with "why" showing the working. State the unit and the rounding rule in the stem ("Round to the nearest tenth."). Only the number is checked, so the student may leave out the unit.`;
const NCLEX_RULES = `Write NCLEX-style (Next Generation NCLEX) items: const NCLEX_RULES = `Write NCLEX-style (Next Generation NCLEX) items:
- Test clinical judgment at the application and analysis level: recognise cues, analyse, prioritise, choose and evaluate actions. Avoid pure recall. - Test clinical judgment at the application and analysis level: recognise cues, analyse, prioritise, choose and evaluate actions. Avoid pure recall.
- Open with a brief, realistic client scenario containing only relevant data (age, diagnosis, key findings, vital signs or lab values with units). - Open with a brief, realistic client scenario containing only relevant data (age, diagnosis, key findings, vital signs or lab values with units).
@ -351,18 +359,21 @@ const NCLEX_RULES = `Write NCLEX-style (Next Generation NCLEX) items:
- Every distractor must be plausible to a student with partial knowledge and wrong for a specific reason. Keep choices parallel in grammar and similar in length. Never use "all of the above" or "none of the above". Do not give the answer away through wording or length. - Every distractor must be plausible to a student with partial knowledge and wrong for a specific reason. Keep choices parallel in grammar and similar in length. Never use "all of the above" or "none of the above". Do not give the answer away through wording or length.
- Multiple-choice items have exactly 4 choices with exactly one best answer. Select-all-that-apply items have 5 or 6 choices with 2 to 5 correct, and the stem ends with "Select all that apply." - Multiple-choice items have exactly 4 choices with exactly one best answer. Select-all-that-apply items have 5 or 6 choices with 2 to 5 correct, and the stem ends with "Select all that apply."
- Use generic drug names. Use current, standard practice. - Use generic drug names. Use current, standard practice.
- The rationale teaches: state why the correct answer is correct, name the principle behind it, and give each choice its own "why".`; - The rationale teaches: state why the correct answer is correct, name the principle behind it, and give each choice its own "why".
${NUMERIC_RULE}`;
const STANDARD_RULES = `Write clear exam-quality questions: const STANDARD_RULES = `Write clear exam-quality questions:
- Each question tests one idea and has one defensible answer set. - Each question tests one idea and has one defensible answer set.
- Mix understanding and application; avoid trivia and trick wording. - Mix understanding and application; avoid trivia and trick wording.
- Distractors are plausible and parallel. Never use "all of the above" or "none of the above". - Distractors are plausible and parallel. Never use "all of the above" or "none of the above".
- Multiple-choice items have 4 choices with exactly one correct. Select-all items have 4 to 6 choices with at least 2 correct. - Multiple-choice items have 4 choices with exactly one correct. Select-all items have 4 to 6 choices with at least 2 correct.
- The rationale explains the correct answer, and each choice gets its own "why".`; - The rationale explains the correct answer, and each choice gets its own "why".
${NUMERIC_RULE}`;
const RECALL_RULES = `Write straightforward recall questions that check key facts, definitions, normal values and classifications. const RECALL_RULES = `Write straightforward recall questions that check key facts, definitions, normal values and classifications.
- Multiple-choice items have 4 choices with exactly one correct. Select-all items have 4 to 6 choices with at least 2 correct. - Multiple-choice items have 4 choices with exactly one correct. Select-all items have 4 to 6 choices with at least 2 correct.
- Keep stems short and unambiguous. Each choice gets a brief "why".`; - Keep stems short and unambiguous. Each choice gets a brief "why".
${NUMERIC_RULE}`;
const CARD_RULES: Record<string, string> = { const CARD_RULES: Record<string, string> = {
concise: 'Each card tests exactly one fact. Fronts are specific questions or terms; backs are short (a phrase or one or two lines).', concise: 'Each card tests exactly one fact. Fronts are specific questions or terms; backs are short (a phrase or one or two lines).',
@ -380,9 +391,71 @@ const NOTE_RULES: Record<string, string> = {
cheat_sheet: 'Write a one-page cheat sheet in Markdown: dense, scannable, organised under short headings, using tables for values, drug classes and comparisons, and bold for must-know facts.', cheat_sheet: 'Write a one-page cheat sheet in Markdown: dense, scannable, organised under short headings, using tables for values, drug classes and comparisons, and bold for must-know facts.',
}; };
function baseSystem(req: GenerateRequest, hasSources: boolean): string { const BASE_ROLE = 'You are an expert educator writing study material for a nursing student. Accuracy is critical: this material is used to prepare for licensing exams.';
/* ------------------------------ editable instructions ------------------------------ */
/**
* The instructions the built-in generator (Generate and the assistant) sends to the model.
* Every entry can be replaced in Settings → Templates; an absent value means the built-in
* wording. These are separate from the instructions for outside chatbots
* (`LLM_INSTRUCTIONS`), which also have to describe the import JSON format.
*/
export const GENERATION_INSTRUCTIONS = {
base: { group: 'All content', label: 'Role', text: BASE_ROLE },
'quiz.nclex': { group: 'Quiz questions', label: 'NCLEX style', text: NCLEX_RULES },
'quiz.standard': { group: 'Quiz questions', label: 'Standard exam style', text: STANDARD_RULES },
'quiz.recall': { group: 'Quiz questions', label: 'Quick recall', text: RECALL_RULES },
'deck.concise': { group: 'Flashcards', label: 'Concise', text: CARD_RULES.concise },
'deck.detailed': { group: 'Flashcards', label: 'Detailed', text: CARD_RULES.detailed },
'deck.medication': { group: 'Flashcards', label: 'Medication', text: CARD_RULES.medication },
'deck.definition': { group: 'Flashcards', label: 'Term and definition', text: CARD_RULES.definition },
'note.study_guide': { group: 'Study guides', label: 'Study guide', text: NOTE_RULES.study_guide },
'note.summary': { group: 'Study guides', label: 'Summary', text: NOTE_RULES.summary },
'note.outline': { group: 'Study guides', label: 'Outline', text: NOTE_RULES.outline },
'note.cheat_sheet': { group: 'Study guides', label: 'Cheat sheet', text: NOTE_RULES.cheat_sheet },
} as const;
export type InstructionKey = keyof typeof GENERATION_INSTRUCTIONS;
const INSTRUCTIONS_SETTING = 'ai.instructions';
export function instructionOverrides(db: DB): Partial<Record<InstructionKey, string>> {
return getSetting<Partial<Record<InstructionKey, string>>>(db, INSTRUCTIONS_SETTING, {});
}
export function instruction(db: DB, key: InstructionKey): string {
const own = instructionOverrides(db)[key];
return own?.trim() ? own : GENERATION_INSTRUCTIONS[key].text;
}
export function listInstructions(db: DB) {
const own = instructionOverrides(db);
return (Object.keys(GENERATION_INSTRUCTIONS) as InstructionKey[]).map((key) => ({
key,
group: GENERATION_INSTRUCTIONS[key].group,
label: GENERATION_INSTRUCTIONS[key].label,
text: own[key]?.trim() ? own[key]! : GENERATION_INSTRUCTIONS[key].text,
builtin: GENERATION_INSTRUCTIONS[key].text,
customized: Boolean(own[key]?.trim()),
}));
}
export const instructionPatchSchema = z.object({
key: z.enum(Object.keys(GENERATION_INSTRUCTIONS) as [InstructionKey, ...InstructionKey[]]),
/** null restores the built-in wording. */
text: z.string().trim().min(10).max(20_000).nullable(),
});
export function saveInstruction(db: DB, input: z.input<typeof instructionPatchSchema>): void {
const { key, text } = instructionPatchSchema.parse(input);
const next = { ...instructionOverrides(db) };
if (text === null || text === GENERATION_INSTRUCTIONS[key].text) delete next[key];
else next[key] = text;
setSetting(db, INSTRUCTIONS_SETTING, next);
}
function baseSystem(db: DB, req: GenerateRequest, hasSources: boolean): string {
const lines = [ const lines = [
'You are an expert educator writing study material for a nursing student. Accuracy is critical: this material is used to prepare for licensing exams.', instruction(db, 'base'),
hasSources hasSources
? 'Base everything on the provided source material. Do not introduce facts that contradict it. You may rely on standard, well-established knowledge only to write plausible distractors and clear explanations.' ? 'Base everything on the provided source material. Do not introduce facts that contradict it. You may rely on standard, well-established knowledge only to write plausible distractors and clear explanations.'
: 'No source material was provided, so rely on current, well-established knowledge. If something is uncertain or varies by institution, prefer the most widely taught standard.', : 'No source material was provided, so rely on current, well-established knowledge. If something is uncertain or varies by institution, prefer the most widely taught standard.',
@ -598,8 +671,8 @@ async function runGeneration(app: AppContext, draftId: string, req: GenerateRequ
const notes: string[] = []; const notes: string[] = [];
const style = req.style ?? 'nclex'; const style = req.style ?? 'nclex';
const rules = isQuiz ? (style === 'nclex' ? NCLEX_RULES : style === 'recall' ? RECALL_RULES : STANDARD_RULES) : CARD_RULES[req.cardStyle ?? 'concise']; const rules = isQuiz ? instruction(db, `quiz.${style}`) : instruction(db, `deck.${req.cardStyle ?? 'concise'}`);
const system = `${baseSystem(req, hasSources)}\n\n${rules}`; const system = `${baseSystem(db, req, hasSources)}\n\n${rules}`;
const sata = req.sataShare ?? (style === 'nclex' ? 0.3 : 0.2); const sata = req.sataShare ?? (style === 'nclex' ? 0.3 : 0.2);
const difficulty = req.difficulty ?? 'mixed'; const difficulty = req.difficulty ?? 'mixed';
@ -609,7 +682,8 @@ async function runGeneration(app: AppContext, draftId: string, req: GenerateRequ
const ask = isQuiz const ask = isQuiz
? [ ? [
`Write ${want} ${style === 'nclex' ? 'NCLEX-style ' : ''}questions${req.focus ? ` about: ${req.focus}` : ''}.`, `Write ${want} ${style === 'nclex' ? 'NCLEX-style ' : ''}questions${req.focus ? ` about: ${req.focus}` : ''}.`,
sata <= 0 ? 'Use only multiple-choice (single) questions.' : sata >= 1 ? 'Use only select-all-that-apply (multi) questions.' : `About ${sataCount} of them should be select-all-that-apply (multi); the rest multiple choice (single).`, sata <= 0 ? 'Use only multiple-choice (single) questions, apart from calculations.' : sata >= 1 ? 'Use only select-all-that-apply (multi) questions, apart from calculations.' : `About ${sataCount} of them should be select-all-that-apply (multi); the rest multiple choice (single).`,
'If the material involves calculations (dosages, IV rates, conversions), write those as numeric questions the student answers by typing the number.',
difficulty === 'mixed' ? 'Mix difficulty: mostly medium, with a few easy and a few hard.' : `Difficulty: ${difficulty}.`, difficulty === 'mixed' ? 'Mix difficulty: mostly medium, with a few easy and a few hard.' : `Difficulty: ${difficulty}.`,
sources.groups.length > 0 ? 'Spread the questions across the excerpts instead of clustering on one. Set "source" to the id of the excerpt each question is based on.' : '', sources.groups.length > 0 ? 'Spread the questions across the excerpts instead of clustering on one. Set "source" to the id of the excerpt each question is based on.' : '',
req.source.deckId ? 'Turn the flashcards into questions: use each card\'s answer as the correct choice and write distractors that a student could confuse with it.' : '', req.source.deckId ? 'Turn the flashcards into questions: use each card\'s answer as the correct choice and write distractors that a student could confuse with it.' : '',
@ -703,7 +777,7 @@ async function generateNote(app: AppContext, draftId: string, req: GenerateReque
const hasSources = sources.groups.length > 0 || Boolean(sources.inline); const hasSources = sources.groups.length > 0 || Boolean(sources.inline);
if (!hasSources && !req.focus) throw badRequest('Choose source material or describe a topic to write about.'); if (!hasSources && !req.focus) throw badRequest('Choose source material or describe a topic to write about.');
const title = defaultTitle(app, req, sources); const title = defaultTitle(app, req, sources);
const system = `${baseSystem(req, hasSources)}\n\n${NOTE_RULES[style]}\n\n${ const system = `${baseSystem(db, req, hasSources)}\n\n${instruction(db, `note.${style}`)}\n\n${
sources.groups.length > 0 ? 'Cite the excerpts you draw on by putting their id in brackets at the end of the relevant line or paragraph, e.g. [c42]. Use only ids that appear in the source.' : '' sources.groups.length > 0 ? 'Cite the excerpts you draw on by putting their id in brackets at the end of the relevant line or paragraph, e.g. [c42]. Use only ids that appear in the source.' : ''
}\nStart directly with the content (no preamble, no title line).`; }\nStart directly with the content (no preamble, no title line).`;
@ -740,7 +814,7 @@ async function generateNote(app: AppContext, draftId: string, req: GenerateReque
task: 'generate', task: 'generate',
purpose: 'study guide', purpose: 'study guide',
modelId: req.modelId, modelId: req.modelId,
system: `${baseSystem(req, true)}\n\nCondense this part of the material into detailed notes: every key concept, value, medication, cause, sign, intervention and warning, as Markdown bullet points under short headings. Keep the bracketed excerpt ids (e.g. [c42]) next to the points they support. Do not add outside information.`, system: `${baseSystem(db, req, true)}\n\nCondense this part of the material into detailed notes: every key concept, value, medication, cause, sign, intervention and warning, as Markdown bullet points under short headings. Keep the bracketed excerpt ids (e.g. [c42]) next to the points they support. Do not add outside information.`,
messages: [{ role: 'user', content: [{ type: 'text', text: `${req.focus ? `Focus on: ${req.focus}\n\n` : ''}SOURCE EXCERPTS (part ${i + 1} of ${passes.length}):\n\n${formatExcerpts(passes[i])}` }] }], messages: [{ role: 'user', content: [{ type: 'text', text: `${req.focus ? `Focus on: ${req.focus}\n\n` : ''}SOURCE EXCERPTS (part ${i + 1} of ${passes.length}):\n\n${formatExcerpts(passes[i])}` }] }],
maxOutputTokens: 6_000, maxOutputTokens: 6_000,
signal, signal,

101
server/ai/localEmbed.ts Normal file
View file

@ -0,0 +1,101 @@
/**
* Built-in embedding model, used for semantic search when no cloud embedding provider is
* configured. Runs on the server's CPU through ONNX Runtime (transformers.js), so it needs no
* API key and costs nothing.
*
* Model: BAAI bge-small-en-v1.5 (ONNX, 8-bit quantised, about 34 MB, 384 dimensions). It is a
* strong small retrieval model; queries get BGE's recommended instruction prefix. The files
* are downloaded from Hugging Face on first use into DATA_DIR/models and reused afterwards.
*
* The library is imported lazily: the app starts (and tests run) without loading ONNX Runtime
* until something actually needs an embedding.
*/
import fs from 'node:fs';
import path from 'node:path';
import { AIError } from './types.ts';
export const LOCAL_PROVIDER_ID = 'local';
export const LOCAL_EMBEDDING_MODEL = 'Xenova/bge-small-en-v1.5';
export const LOCAL_EMBEDDING_LABEL = 'bge-small-en-v1.5 (built in)';
export const LOCAL_EMBEDDING_DIMS = 384;
const QUERY_PREFIX = 'Represent this sentence for searching relevant passages: ';
/** Inputs per forward pass: small enough to keep memory flat on a home server. */
const BATCH = 16;
/** About 512 tokens, the model's window. Longer input is truncated by the tokenizer anyway. */
const MAX_CHARS = 2000;
type Extractor = (texts: string[], opts: { pooling: 'cls' | 'mean'; normalize: boolean }) => Promise<{ tolist(): number[][] }>;
const state: { extractor: Promise<Extractor> | null; cacheDir: string; status: 'idle' | 'loading' | 'ready' | 'error'; error: string } = {
extractor: null,
cacheDir: '',
status: 'idle',
error: '',
};
export function localModelDir(dataDir: string): string {
return path.join(dataDir, 'models');
}
/** True when the model files are already on disk (no download needed). */
export function localModelDownloaded(dataDir: string): boolean {
const dir = path.join(localModelDir(dataDir), ...LOCAL_EMBEDDING_MODEL.split('/'));
try {
return fs.existsSync(path.join(dir, 'onnx', 'model_quantized.onnx')) && fs.existsSync(path.join(dir, 'tokenizer.json'));
} catch {
return false;
}
}
export function localModelStatus(dataDir: string) {
return { model: LOCAL_EMBEDDING_MODEL, label: LOCAL_EMBEDDING_LABEL, dimensions: LOCAL_EMBEDDING_DIMS, downloaded: localModelDownloaded(dataDir), status: state.status, error: state.error };
}
async function load(dataDir: string): Promise<Extractor> {
const cacheDir = localModelDir(dataDir);
if (state.extractor && state.cacheDir === cacheDir) return state.extractor;
state.cacheDir = cacheDir;
state.status = 'loading';
state.error = '';
state.extractor = (async () => {
fs.mkdirSync(cacheDir, { recursive: true });
let lib: typeof import('@huggingface/transformers');
try {
lib = await import('@huggingface/transformers');
} catch (err) {
throw new AIError('unsupported', 'The built-in embedding model is not available in this installation.', { cause: err });
}
lib.env.cacheDir = cacheDir;
lib.env.allowRemoteModels = true;
lib.env.allowLocalModels = true;
lib.env.localModelPath = cacheDir;
const extractor = await lib.pipeline('feature-extraction', LOCAL_EMBEDDING_MODEL, { dtype: 'q8' });
return extractor as unknown as Extractor;
})();
try {
const ready = await state.extractor;
state.status = 'ready';
return ready;
} catch (err) {
state.extractor = null;
state.status = 'error';
const message = err instanceof AIError ? err.message : `The built-in embedding model could not be loaded: ${err instanceof Error ? err.message : String(err)}`;
state.error = message;
throw err instanceof AIError ? err : new AIError('network', `${message}. It is downloaded once (about 35 MB) from huggingface.co; check that the server can reach the internet.`, { cause: err, retryable: true });
}
}
/** Embeds texts with the built-in model. Vectors come back L2-normalised. */
export async function localEmbed(dataDir: string, texts: string[], purpose: 'document' | 'query', signal?: AbortSignal): Promise<number[][]> {
const extractor = await load(dataDir);
const out: number[][] = [];
for (let i = 0; i < texts.length; i += BATCH) {
if (signal?.aborted) throw new AIError('aborted', 'The request was cancelled.');
const batch = texts.slice(i, i + BATCH).map((t) => (purpose === 'query' ? QUERY_PREFIX : '') + (t.slice(0, MAX_CHARS) || ' '));
const tensor = await extractor(batch, { pooling: 'cls', normalize: true });
out.push(...tensor.tolist());
// Let the event loop serve requests between batches; indexing runs in the background.
await new Promise((resolve) => setImmediate(resolve));
}
return out;
}

View file

@ -38,7 +38,7 @@ import {
type TestResult, type TestResult,
} from '../types.ts'; } from '../types.ts';
import { lookupModelDefaults } from './catalog.ts'; import { lookupModelDefaults } from './catalog.ts';
import { isChatModelId, makeUsage, num, parseArgsStrict, parseToolArguments, runTest, str, TEST_TIMEOUT_MS, withCatalogDefaults } from './common.ts'; import { isChatModelId, makeUsage, nearestEffort, num, parseArgsStrict, parseToolArguments, runTest, str, TEST_TIMEOUT_MS, withCatalogDefaults } from './common.ts';
import { ensureOk, errorFromProvider, httpRequest, isRecord, requestJson, sseJson, trimBaseUrl, type ErrorContext } from './http.ts'; import { ensureOk, errorFromProvider, httpRequest, isRecord, requestJson, sseJson, trimBaseUrl, type ErrorContext } from './http.ts';
type Json = Record<string, unknown>; type Json = Record<string, unknown>;
@ -120,7 +120,10 @@ export function claudeProfile(model: string): ClaudeProfile {
} }
/** Thinking budgets for the legacy `budget_tokens` models. */ /** Thinking budgets for the legacy `budget_tokens` models. */
const LEGACY_BUDGET = { low: 2_048, medium: 8_192, high: 16_384 } as const; const LEGACY_BUDGET = { minimal: 1_024, low: 2_048, medium: 8_192, high: 16_384, xhigh: 24_576, max: 32_000 } as const;
/** `output_config.effort` levels. "xhigh" exists on the newest models only; a rejection steps it down. */
const CLAUDE_EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'] as const;
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
/* Request building */ /* Request building */
@ -133,6 +136,8 @@ interface BuildOptions {
useFallbacks: boolean; useFallbacks: boolean;
eagerToolInput: boolean; eagerToolInput: boolean;
promptCache: boolean; promptCache: boolean;
/** Highest effort level the model accepted, after a rejection. */
effortCap?: (typeof CLAUDE_EFFORTS)[number];
} }
/** Tool-call ids must match ^[a-zA-Z0-9_-]+$; ids minted by other providers may not. */ /** Tool-call ids must match ^[a-zA-Z0-9_-]+$; ids minted by other providers may not. */
@ -268,7 +273,7 @@ function buildBody(req: ChatRequest, profile: ClaudeProfile, opts: BuildOptions)
// `display: "summarized"` because these models hide the reasoning text by // `display: "summarized"` because these models hide the reasoning text by
// default, which would look like a long pause in the UI. // default, which would look like a long pause in the UI.
body.thinking = adaptive; body.thinking = adaptive;
if (effort) outputConfig.effort = effort; if (effort) outputConfig.effort = opts.effortCap ? nearestEffort(effort, CLAUDE_EFFORTS.filter((e) => CLAUDE_EFFORTS.indexOf(e) <= CLAUDE_EFFORTS.indexOf(opts.effortCap!))) : nearestEffort(effort, CLAUDE_EFFORTS);
} else if (effort) { } else if (effort) {
// Forced tool use cannot be combined with thinking on the older generations. // Forced tool use cannot be combined with thinking on the older generations.
if (profile.thinking === 'opt_in' && !forcing) body.thinking = adaptive; if (profile.thinking === 'opt_in' && !forcing) body.thinking = adaptive;
@ -276,7 +281,7 @@ function buildBody(req: ChatRequest, profile: ClaudeProfile, opts: BuildOptions)
const budget = Math.min(LEGACY_BUDGET[effort], maxTokens - 1_024); // must be < max_tokens, min 1024 const budget = Math.min(LEGACY_BUDGET[effort], maxTokens - 1_024); // must be < max_tokens, min 1024
if (budget >= 1_024) body.thinking = { type: 'enabled', budget_tokens: budget }; if (budget >= 1_024) body.thinking = { type: 'enabled', budget_tokens: budget };
} }
if (profile.effort) outputConfig.effort = effort; if (profile.effort) outputConfig.effort = opts.effortCap ? nearestEffort(effort, CLAUDE_EFFORTS.filter((e) => CLAUDE_EFFORTS.indexOf(e) <= CLAUDE_EFFORTS.indexOf(opts.effortCap!))) : nearestEffort(effort, CLAUDE_EFFORTS);
} }
if (Object.keys(outputConfig).length > 0) body.output_config = outputConfig; if (Object.keys(outputConfig).length > 0) body.output_config = outputConfig;
} }
@ -375,6 +380,7 @@ async function* stream(cfg: ProviderConfig, req: ChatRequest): AsyncGenerator<St
else if (opts.useFallbacks && /fallback|anthropic-beta/i.test(detail)) opts.useFallbacks = false; else if (opts.useFallbacks && /fallback|anthropic-beta/i.test(detail)) opts.useFallbacks = false;
else if (opts.eagerToolInput && /eager_input_streaming/i.test(detail)) opts.eagerToolInput = false; else if (opts.eagerToolInput && /eager_input_streaming/i.test(detail)) opts.eagerToolInput = false;
else if (opts.promptCache && /cache_control/i.test(detail)) opts.promptCache = false; else if (opts.promptCache && /cache_control/i.test(detail)) opts.promptCache = false;
else if (/effort/i.test(detail) && opts.effortCap !== 'medium' && req.reasoningEffort && req.reasoningEffort !== 'none') opts.effortCap = opts.effortCap === 'high' ? 'medium' : opts.effortCap === 'xhigh' ? 'high' : 'xhigh';
else throw err; else throw err;
} }
} }

View file

@ -129,10 +129,28 @@ const GEMINI: Record<string, Entry> = {
'gemini-2.5-flash-lite': { label: 'Gemini 2.5 Flash-Lite', priceIn: 0.1, priceOut: 0.4, capabilities: GEMINI_CAPS }, 'gemini-2.5-flash-lite': { label: 'Gemini 2.5 Flash-Lite', priceIn: 0.1, priceOut: 0.4, capabilities: GEMINI_CAPS },
}; };
/* ------------------------------------------------------------------ */
/* DeepSeek */
/* Prices and limits: https://api-docs.deepseek.com/quick_start/pricing (fetched 2026-11-15)
/* Peak-hour list prices are stored. Off-peak hours (everything outside 01:00-04:00 and
/* 06:00-10:00 UTC, Monday to Friday) cost half; `priceMultiplier` applies that per call.
/* deepseek-v4-flash / deepseek-v4-flash-vision-exp are retired aliases served by
/* deepseek-flash at the Flash price.
/* ------------------------------------------------------------------ */
const DS_LIMITS = { contextWindow: 1_048_576, maxOutput: 393_216 };
const DEEPSEEK: Record<string, Entry> = {
'deepseek-flash': { label: 'DeepSeek V4.1 Flash', ...DS_LIMITS, priceIn: 0.3, priceCachedIn: 0.006, priceOut: 1.2, capabilities: { tools: true, vision: true, pdf: false, reasoning: true, temperature: true } },
'deepseek-v4-flash': { label: 'DeepSeek V4 Flash (alias of Flash)', ...DS_LIMITS, priceIn: 0.3, priceCachedIn: 0.006, priceOut: 1.2, capabilities: { tools: true, vision: true, pdf: false, reasoning: true, temperature: true } },
'deepseek-v4-pro': { label: 'DeepSeek V4 Pro', ...DS_LIMITS, priceIn: 1.32, priceCachedIn: 0.044, priceOut: 3.96, capabilities: { tools: true, vision: false, pdf: false, reasoning: true, temperature: true } },
};
const TABLES: Record<ProviderKind, Record<string, Entry>> = { const TABLES: Record<ProviderKind, Record<string, Entry>> = {
openai: OPENAI, openai: OPENAI,
anthropic: ANTHROPIC, anthropic: ANTHROPIC,
gemini: GEMINI, gemini: GEMINI,
deepseek: DEEPSEEK,
// Aggregators and local servers host arbitrary models at their own prices. // Aggregators and local servers host arbitrary models at their own prices.
openai_compatible: {}, openai_compatible: {},
ollama: {}, ollama: {},
@ -168,6 +186,7 @@ function lookupIn(table: Record<string, Entry>, id: string): Partial<DiscoveredM
// capabilities are a fair guess, the price is not. // capabilities are a fair guess, the price is not.
delete out.priceIn; delete out.priceIn;
delete out.priceOut; delete out.priceOut;
delete out.priceCachedIn;
} }
return out; return out;
} }
@ -185,11 +204,12 @@ export function lookupModelDefaults(kind: ProviderKind, modelId: string): Partia
// Routers name models "<vendor>/<model>" (`anthropic/claude-sonnet-5-5`). // Routers name models "<vendor>/<model>" (`anthropic/claude-sonnet-5-5`).
// Borrow capabilities and limits from the vendor's table, never its prices. // Borrow capabilities and limits from the vendor's table, never its prices.
const bare = id.slice(id.lastIndexOf('/') + 1).replace(/:[a-z]+$/, ''); const bare = id.slice(id.lastIndexOf('/') + 1).replace(/:[a-z]+$/, '');
for (const table of [OPENAI, ANTHROPIC, GEMINI]) { for (const table of [OPENAI, ANTHROPIC, GEMINI, DEEPSEEK]) {
const hit = lookupIn(table, bare); const hit = lookupIn(table, bare);
if (Object.keys(hit).length > 0) { if (Object.keys(hit).length > 0) {
delete hit.priceIn; delete hit.priceIn;
delete hit.priceOut; delete hit.priceOut;
delete hit.priceCachedIn;
// Temperature limits are properties of the first-party APIs, not of the router. // Temperature limits are properties of the first-party APIs, not of the router.
if (hit.capabilities) delete hit.capabilities.temperature; if (hit.capabilities) delete hit.capabilities.temperature;
return hit; return hit;
@ -204,3 +224,51 @@ export function lookupModelDefaults(kind: ProviderKind, modelId: string): Partia
export function catalogModelIds(kind: ProviderKind): string[] { export function catalogModelIds(kind: ProviderKind): string[] {
return Object.keys(TABLES[kind]); return Object.keys(TABLES[kind]);
} }
/**
* What a cache-hit input token costs when a model has no cached price of its own, as a
* fraction of the normal input price. These are the providers' published discounts for
* their current models: OpenAI GPT-5 and later, Claude cache reads and Gemini 2.5 and later
* all bill cached input at 10%. Older OpenAI models (GPT-4.1 25%, GPT-4o / o-series 50%)
* discount less. Servers behind the compatible adapter and Ollama have no known discount.
*/
export function cachedInputRatio(kind: ProviderKind, modelId: string): number {
const id = modelId.slice(modelId.lastIndexOf('/') + 1);
switch (kind) {
case 'openai':
if (/^gpt-4\.1/.test(id)) return 0.25;
if (/^(gpt-4o|o\d)/.test(id)) return 0.5;
return 0.1;
case 'anthropic':
case 'gemini':
return 0.1;
case 'deepseek':
return 0.02;
default:
return 1;
}
}
/** USD per million cached input tokens: the model's own price when set, otherwise the provider discount. */
export function cachedInputPrice(kind: ProviderKind, modelId: string, priceIn: number | null, priceCachedIn: number | null): number {
if (priceCachedIn !== null && priceCachedIn !== undefined) return priceCachedIn;
return (priceIn ?? 0) * cachedInputRatio(kind, modelId);
}
/** Cache writes: Claude bills writing the (5-minute) prompt cache at 1.25x the input price. */
export function cacheWriteRatio(kind: ProviderKind): number {
return kind === 'anthropic' ? 1.25 : 1;
}
/**
* Time-of-day pricing. DeepSeek charges half its list price outside peak hours
* (01:00-04:00 and 06:00-10:00 UTC, Monday to Friday).
*/
export function priceMultiplier(kind: ProviderKind, at: number = Date.now()): number {
if (kind !== 'deepseek') return 1;
const d = new Date(at);
const day = d.getUTCDay();
const hour = d.getUTCHours();
const peak = day >= 1 && day <= 5 && ((hour >= 1 && hour < 4) || (hour >= 6 && hour < 10));
return peak ? 1 : 0.5;
}

View file

@ -4,7 +4,7 @@
* connection-test wrapper. * connection-test wrapper.
*/ */
import { jsonrepair } from 'jsonrepair'; import { jsonrepair } from 'jsonrepair';
import { AIError, type DiscoveredModel, type ProviderKind, type TestResult, type Usage } from '../types.ts'; import { AIError, REASONING_EFFORTS, type DiscoveredModel, type ProviderKind, type ReasoningEffort, type TestResult, type Usage } from '../types.ts';
import { lookupModelDefaults } from './catalog.ts'; import { lookupModelDefaults } from './catalog.ts';
import { isRecord } from './http.ts'; import { isRecord } from './http.ts';
@ -151,3 +151,22 @@ export async function runTest(label: string, check: () => Promise<{ modelCount?:
/** Timeout used by `test()` so a dead endpoint fails fast instead of hanging the settings page. */ /** Timeout used by `test()` so a dead endpoint fails fast instead of hanging the settings page. */
export const TEST_TIMEOUT_MS = 20_000; export const TEST_TIMEOUT_MS = 20_000;
/**
* Maps a requested effort onto the closest level a provider accepts. Ties go to the higher
* level, so "medium" on a low/high-only API becomes "high" rather than silently weaker.
*/
export function nearestEffort<T extends string>(effort: ReasoningEffort, allowed: readonly T[]): T {
const rank = (e: string) => REASONING_EFFORTS.indexOf(e as ReasoningEffort);
const want = rank(effort);
let best = allowed[0];
let bestDistance = Number.POSITIVE_INFINITY;
for (const level of allowed) {
const d = Math.abs(rank(level) - want);
if (d < bestDistance || (d === bestDistance && rank(level) > rank(best))) {
best = level;
bestDistance = d;
}
}
return best;
}

View file

@ -0,0 +1,112 @@
/**
* DeepSeek — Chat Completions at https://api.deepseek.com.
* https://api-docs.deepseek.com/api/create-chat-completion/
* https://api-docs.deepseek.com/guides/thinking_mode/
*
* The wire format is OpenAI-compatible, so this reuses the compatible adapter's engine with
* the differences DeepSeek documents:
* - Thinking is ON by default. `thinking: {type: "disabled"}` turns it off;
* `reasoning_effort` accepts none / low / high / max.
* - In thinking mode `tool_choice: "required"` and named tool choices are rejected with a
* 400. Structured generation keeps thinking on (answer keys are noticeably more accurate
* with it) and asks for the tool call in the prompt with `tool_choice: "auto"`. Only when
* the effort is set to "none" is thinking off, and then the tool choice is forced.
* - When tools are present, the `reasoning_content` of every earlier assistant turn must be
* sent back, or the API answers 400. It is kept in `providerData` and replayed.
* - Usage reports `prompt_cache_hit_tokens`; cache hits are billed at a much lower rate.
* - `/models` lists context window, output limit, input modalities and effort levels.
*/
import { AIError, type ChatRequest, type DiscoveredModel, type ModelCapabilities, type ProviderAdapter, type ProviderConfig, type TestResult } from '../types.ts';
import { isChatModelId, nearestEffort, num, runTest, str, TEST_TIMEOUT_MS, withCatalogDefaults } from './common.ts';
import { isRecord, requestJson, trimBaseUrl } from './http.ts';
import { streamChatCompletions, type CompatOptions } from './openaiCompatible.ts';
export const DEEPSEEK_BASE_URL = 'https://api.deepseek.com';
const LABEL = 'DeepSeek';
const EFFORTS = ['low', 'high', 'max'] as const;
function base(cfg: ProviderConfig): string {
return trimBaseUrl(cfg.baseUrl?.trim() || DEEPSEEK_BASE_URL);
}
/** "none" turns thinking off; a model marked as not reasoning is treated the same way. */
function effortOf(req: ChatRequest): ChatRequest['reasoningEffort'] {
return req.capabilities?.reasoning === false ? 'none' : req.reasoningEffort;
}
function options(cfg: ProviderConfig): CompatOptions {
if (!cfg.apiKey) throw new AIError('not_configured', `Add your DeepSeek API key for "${cfg.name}" in Settings.`);
return {
kind: 'deepseek',
label: cfg.name || LABEL,
// DeepSeek serves the same API at the root and under /v1; the explicit /v1 keeps the
// compatible engine from guessing.
baseUrl: `${base(cfg)}/v1`,
apiKey: cfg.apiKey,
headers: cfg.headers,
replayReasoning: true,
forcedToolChoice: (req) => effortOf(req) === 'none',
adjustBody: (body, req) => {
const effort = effortOf(req);
delete body.reasoning_effort;
if (effort === 'none' || body.tool_choice === 'required' || isRecord(body.tool_choice)) {
// Non-thinking mode (also the only mode that accepts a forced tool choice).
body.thinking = { type: 'disabled' };
} else {
body.thinking = { type: 'enabled' };
if (effort) body.reasoning_effort = nearestEffort(effort, EFFORTS);
// Sampling parameters have no effect in thinking mode; leave them out.
delete body.temperature;
}
},
};
}
async function listModels(cfg: ProviderConfig, signal?: AbortSignal, timeoutMs?: number): Promise<DiscoveredModel[]> {
const o = options(cfg);
const res = await requestJson(`${base(cfg)}/models`, {
provider: o.label,
secrets: [o.apiKey, ...Object.values(o.headers ?? {})],
headers: { ...o.headers, Authorization: `Bearer ${o.apiKey}` },
signal,
firstByteTimeoutMs: timeoutMs,
totalTimeoutMs: timeoutMs,
});
const list = isRecord(res) && Array.isArray(res.data) ? res.data : [];
const found: DiscoveredModel[] = [];
for (const m of list) {
if (!isRecord(m)) continue;
const id = str(m.id);
if (!id || !isChatModelId(id)) continue;
const model: DiscoveredModel = { id };
if (str(m.name) && str(m.name) !== id) model.label = str(m.name);
if (num(m.context_window)) model.contextWindow = num(m.context_window);
if (num(m.max_output_tokens)) model.maxOutput = num(m.max_output_tokens);
const caps: Partial<ModelCapabilities> = { tools: true, pdf: false };
if (Array.isArray(m.input_modalities)) caps.vision = m.input_modalities.includes('image');
if (isRecord(m.effort)) caps.reasoning = true;
model.capabilities = caps;
found.push(model);
}
return withCatalogDefaults('deepseek', found);
}
async function test(cfg: ProviderConfig): Promise<TestResult> {
return runTest(cfg.name || LABEL, async () => ({ modelCount: (await listModels(cfg, undefined, TEST_TIMEOUT_MS)).length }));
}
export const deepseekAdapter: ProviderAdapter = {
kind: 'deepseek',
meta: {
label: 'DeepSeek',
defaultBaseUrl: DEEPSEEK_BASE_URL,
requiresApiKey: true,
requiresBaseUrl: false,
supportsDiscovery: true,
docsUrl: 'https://platform.deepseek.com/api_keys',
keyHint: 'Starts with sk-',
},
stream: (cfg, req) => streamChatCompletions(options(cfg), req),
listModels: (cfg, signal) => listModels(cfg, signal),
test,
};

View file

@ -29,7 +29,7 @@ import { type EmbedRequest, type EmbedResult,
type StreamEvent, type StreamEvent,
type TestResult, type TestResult,
} from '../types.ts'; } from '../types.ts';
import { isChatModelId, makeUsage, newToolCallId, num, runTest, str, TEST_TIMEOUT_MS, withCatalogDefaults } from './common.ts'; import { isChatModelId, makeUsage, nearestEffort, newToolCallId, num, runTest, str, TEST_TIMEOUT_MS, withCatalogDefaults } from './common.ts';
import { ensureOk, errorFromProvider, httpRequest, isRecord, requestJson, sseJson, trimBaseUrl, type ErrorContext, type HttpResponse } from './http.ts'; import { ensureOk, errorFromProvider, httpRequest, isRecord, requestJson, sseJson, trimBaseUrl, type ErrorContext, type HttpResponse } from './http.ts';
type Json = Record<string, unknown>; type Json = Record<string, unknown>;
@ -140,7 +140,8 @@ function thinkingStyleFor(model: string): ThinkingStyle {
return 'off'; return 'off';
} }
const BUDGETS = { none: 0, low: 2_048, medium: 8_192, high: 24_576 } as const; const BUDGETS = { none: 0, minimal: 512, low: 2_048, medium: 8_192, high: 24_576, xhigh: 32_768, max: 32_768 } as const;
const GEMINI_LEVELS = ['minimal', 'low', 'medium', 'high'] as const;
function buildBody(req: ChatRequest, thinking: ThinkingStyle, jsonMode: boolean): Json { function buildBody(req: ChatRequest, thinking: ThinkingStyle, jsonMode: boolean): Json {
const caps = req.capabilities ?? {}; const caps = req.capabilities ?? {};
@ -165,7 +166,7 @@ function buildBody(req: ChatRequest, thinking: ThinkingStyle, jsonMode: boolean)
const effort = req.reasoningEffort; const effort = req.reasoningEffort;
if (thinking === 'level') { if (thinking === 'level') {
const cfg: Json = { includeThoughts: true }; const cfg: Json = { includeThoughts: true };
if (effort) cfg.thinkingLevel = effort === 'none' ? 'minimal' : effort; if (effort) cfg.thinkingLevel = nearestEffort(effort, GEMINI_LEVELS);
gen.thinkingConfig = cfg; gen.thinkingConfig = cfg;
} else if (effort) { } else if (effort) {
// 2.5 Pro cannot switch thinking off; its minimum budget is 128 tokens. // 2.5 Pro cannot switch thinking off; its minimum budget is 128 tokens.

View file

@ -1,5 +1,6 @@
import { AIError, type ProviderAdapter, type ProviderKind } from '../types.ts'; import { AIError, type ProviderAdapter, type ProviderKind } from '../types.ts';
import { anthropicAdapter } from './anthropic.ts'; import { anthropicAdapter } from './anthropic.ts';
import { deepseekAdapter } from './deepseek.ts';
import { geminiAdapter } from './gemini.ts'; import { geminiAdapter } from './gemini.ts';
import { ollamaAdapter } from './ollama.ts'; import { ollamaAdapter } from './ollama.ts';
import { openaiAdapter } from './openai.ts'; import { openaiAdapter } from './openai.ts';
@ -9,6 +10,7 @@ const ADAPTERS: Record<ProviderKind, ProviderAdapter> = {
openai: openaiAdapter, openai: openaiAdapter,
anthropic: anthropicAdapter, anthropic: anthropicAdapter,
gemini: geminiAdapter, gemini: geminiAdapter,
deepseek: deepseekAdapter,
openai_compatible: openaiCompatibleAdapter, openai_compatible: openaiCompatibleAdapter,
ollama: ollamaAdapter, ollama: ollamaAdapter,
}; };
@ -23,4 +25,4 @@ export function listAdapterMeta(): Array<{ kind: ProviderKind } & ProviderAdapte
return (Object.keys(ADAPTERS) as ProviderKind[]).map((kind) => ({ kind, ...ADAPTERS[kind].meta })); return (Object.keys(ADAPTERS) as ProviderKind[]).map((kind) => ({ kind, ...ADAPTERS[kind].meta }));
} }
export { CATALOG_UPDATED, lookupModelDefaults } from './catalog.ts'; export { CATALOG_UPDATED, cachedInputPrice, cacheWriteRatio, lookupModelDefaults, priceMultiplier } from './catalog.ts';

View file

@ -103,6 +103,9 @@ function toInput(messages: ChatMessage[], caps: Partial<ModelCapabilities>, drop
return input; return input;
} }
/** The next value to try when a model rejects a reasoning effort. */
const OPENAI_EFFORT_FALLBACK: Record<string, string | null> = { none: 'minimal', minimal: 'low', low: null, medium: null, high: null, xhigh: 'high' };
interface Flags { interface Flags {
/** Value sent as reasoning.effort, or null to omit the field. */ /** Value sent as reasoning.effort, or null to omit the field. */
effort: string | null; effort: string | null;
@ -139,8 +142,9 @@ function buildBody(req: ChatRequest, flags: Flags): Json {
async function* stream(cfg: ProviderConfig, req: ChatRequest): AsyncGenerator<StreamEvent> { async function* stream(cfg: ProviderConfig, req: ChatRequest): AsyncGenerator<StreamEvent> {
const ctx = errorContext(cfg); const ctx = errorContext(cfg);
const flags: Flags = { const flags: Flags = {
// "none" is only understood by recent models; if it is rejected we fall back to "low". // OpenAI's top level is "xhigh". "none" and "xhigh" are only understood by recent
effort: req.reasoningEffort ?? null, // models; a rejected value steps towards "medium" and is finally omitted.
effort: req.reasoningEffort ? (req.reasoningEffort === 'max' ? 'xhigh' : req.reasoningEffort) : null,
summary: true, summary: true,
temperature: true, temperature: true,
dropReasoning: false, dropReasoning: false,
@ -156,7 +160,7 @@ async function* stream(cfg: ProviderConfig, req: ChatRequest): AsyncGenerator<St
} catch (err) { } catch (err) {
if (!(err instanceof AIError) || err.status !== 400 || attempt >= 5) throw err; if (!(err instanceof AIError) || err.status !== 400 || attempt >= 5) throw err;
const detail = (err.providerMessage ?? '').toLowerCase(); const detail = (err.providerMessage ?? '').toLowerCase();
if (flags.effort && /reasoning\.effort|reasoning_effort|effort/.test(detail)) flags.effort = flags.effort === 'none' ? 'minimal' : flags.effort === 'minimal' ? 'low' : null; if (flags.effort && /reasoning\.effort|reasoning_effort|effort/.test(detail)) flags.effort = OPENAI_EFFORT_FALLBACK[flags.effort] ?? null;
else if (flags.summary && /summary/.test(detail)) flags.summary = false; else if (flags.summary && /summary/.test(detail)) flags.summary = false;
else if (flags.include && /include|encrypted_content/.test(detail)) flags.include = false; else if (flags.include && /include|encrypted_content/.test(detail)) flags.include = false;
else if (flags.temperature && /temperature/.test(detail)) flags.temperature = false; else if (flags.temperature && /temperature/.test(detail)) flags.temperature = false;

View file

@ -27,10 +27,10 @@ import { type EmbedRequest, type EmbedResult,
type StreamEvent, type StreamEvent,
type TestResult, type TestResult,
} from '../types.ts'; } from '../types.ts';
import { parseEmbeddings, dataUrl, isChatModelId, makeUsage, newToolCallId, num, parseArgsStrict, parseToolArguments, runTest, str, TEST_TIMEOUT_MS, withCatalogDefaults } from './common.ts'; import { parseEmbeddings, dataUrl, isChatModelId, makeUsage, nearestEffort, newToolCallId, num, parseArgsStrict, parseToolArguments, runTest, str, TEST_TIMEOUT_MS, withCatalogDefaults } from './common.ts';
import { ensureOk, errorFromProvider, hostOf, httpRequest, isLocalUrl, isRecord, requestJson, sseJson, trimBaseUrl, type ErrorContext, type HttpResponse } from './http.ts'; import { ensureOk, errorFromProvider, hostOf, httpRequest, isLocalUrl, isRecord, requestJson, sseJson, trimBaseUrl, type ErrorContext, type HttpResponse } from './http.ts';
type Json = Record<string, unknown>; export type Json = Record<string, unknown>;
/** Accepts ".../v1", ".../v1/", ".../v1/chat/completions" or a bare host and returns the API root. */ /** Accepts ".../v1", ".../v1/", ".../v1/chat/completions" or a bare host and returns the API root. */
export function normalizeCompatBase(url: string): string { export function normalizeCompatBase(url: string): string {
@ -51,8 +51,26 @@ export interface CompatOptions {
baseUrl: string; baseUrl: string;
apiKey: string | null; apiKey: string | null;
headers?: Record<string, string>; headers?: Record<string, string>;
/**
* Server-specific request tweaks (DeepSeek's `thinking` switch, its effort levels...).
* Called on the finished body before it is sent.
*/
adjustBody?: (body: Json, req: ChatRequest) => void;
/**
* The server requires the reasoning text of earlier assistant turns to be sent back
* (`reasoning_content`), as DeepSeek does in thinking mode with tools.
*/
replayReasoning?: boolean;
/**
* Whether `required` / named tool choices may be sent for this request. When false the
* tool stays available with `auto` and the system prompt asks for the call instead.
*/
forcedToolChoice?: (req: ChatRequest) => boolean;
} }
/** Levels sent as `reasoning_effort` by default. "max" has no OpenAI-style equivalent. */
const COMPAT_EFFORTS = ['minimal', 'low', 'medium', 'high', 'xhigh'] as const;
function userContent(parts: ContentPart[], caps: Partial<ModelCapabilities>): string | Json[] { function userContent(parts: ContentPart[], caps: Partial<ModelCapabilities>): string | Json[] {
const blocks: Json[] = []; const blocks: Json[] = [];
for (const p of parts) { for (const p of parts) {
@ -72,7 +90,7 @@ function userContent(parts: ContentPart[], caps: Partial<ModelCapabilities>): st
return blocks; return blocks;
} }
export function toChatMessages(req: ChatRequest, systemRole: 'system' | 'developer' = 'system'): Json[] { export function toChatMessages(req: ChatRequest, systemRole: 'system' | 'developer' = 'system', replay?: { kind: ProviderKind }): Json[] {
const caps = req.capabilities ?? {}; const caps = req.capabilities ?? {};
const out: Json[] = []; const out: Json[] = [];
if (req.system?.trim()) out.push({ role: systemRole, content: req.system.trim() }); if (req.system?.trim()) out.push({ role: systemRole, content: req.system.trim() });
@ -82,6 +100,12 @@ export function toChatMessages(req: ChatRequest, systemRole: 'system' | 'develop
const calls = msg.content.filter((p) => p.type === 'tool_call') as Extract<ContentPart, { type: 'tool_call' }>[]; const calls = msg.content.filter((p) => p.type === 'tool_call') as Extract<ContentPart, { type: 'tool_call' }>[];
if (!text && calls.length === 0) continue; if (!text && calls.length === 0) continue;
const wire: Json = { role: 'assistant', content: text || null }; const wire: Json = { role: 'assistant', content: text || null };
if (replay) {
// Same server: hand back its reasoning verbatim. A turn written by another provider
// has none, which these servers accept as an empty string.
const pd = msg.providerData;
wire.reasoning_content = pd?.kind === replay.kind && isRecord(pd.data) && typeof pd.data.reasoning_content === 'string' ? pd.data.reasoning_content : '';
}
if (calls.length > 0) { if (calls.length > 0) {
wire.tool_calls = calls.map((c) => ({ id: c.id, type: 'function', function: { name: c.name, arguments: JSON.stringify(c.input ?? {}) } })); wire.tool_calls = calls.map((c) => ({ id: c.id, type: 'function', function: { name: c.name, arguments: JSON.stringify(c.input ?? {}) } }));
} }
@ -103,6 +127,8 @@ export function toChatMessages(req: ChatRequest, systemRole: 'system' | 'develop
interface BodyFlags { interface BodyFlags {
tools: boolean; tools: boolean;
/** Send `required` / named tool choices as such; false = ask for the call in the prompt instead. */
forcedChoice: boolean;
usage: boolean; usage: boolean;
jsonMode: boolean; jsonMode: boolean;
temperature: boolean; temperature: boolean;
@ -110,23 +136,40 @@ interface BodyFlags {
maxKey: 'max_tokens' | 'max_completion_tokens' | null; maxKey: 'max_tokens' | 'max_completion_tokens' | null;
} }
function buildBody(req: ChatRequest, flags: BodyFlags): Json { function forcedToolNote(choice: ChatRequest['toolChoice']): string | null {
if (choice === 'required') return 'For this turn you must call one of the available tools. Begin your response with the tool call.';
if (isRecord(choice)) return `For this turn you must call the \`${choice.name}\` tool. Begin your response with that tool call and do not answer in plain text.`;
return null;
}
function buildBody(req: ChatRequest, flags: BodyFlags, o: CompatOptions): Json {
const caps = req.capabilities ?? {}; const caps = req.capabilities ?? {};
const body: Json = { model: req.model, messages: toChatMessages(req), stream: true }; const sendTools = flags.tools && caps.tools !== false && Boolean(req.tools?.length);
const note = sendTools && !flags.forcedChoice ? forcedToolNote(req.toolChoice) : null;
const effective = note ? { ...req, system: [req.system?.trim(), note].filter(Boolean).join('\n\n') } : req;
const body: Json = { model: req.model, messages: toChatMessages(effective, 'system', o.replayReasoning ? { kind: o.kind } : undefined), stream: true };
if (flags.usage) body.stream_options = { include_usage: true }; if (flags.usage) body.stream_options = { include_usage: true };
if (flags.tools && caps.tools !== false && req.tools?.length) { if (sendTools) {
body.tools = req.tools.map((t) => ({ type: 'function', function: { name: t.name, description: t.description, parameters: { type: 'object', ...t.parameters } } })); body.tools = req.tools!.map((t) => ({ type: 'function', function: { name: t.name, description: t.description, parameters: { type: 'object', ...t.parameters } } }));
const choice = req.toolChoice; const choice = req.toolChoice;
if (choice === 'none' || choice === 'required' || choice === 'auto') body.tool_choice = choice; if (choice === 'none' || choice === 'auto') body.tool_choice = choice;
else if (isRecord(choice)) body.tool_choice = { type: 'function', function: { name: choice.name } }; else if (choice === 'required') body.tool_choice = flags.forcedChoice ? 'required' : 'auto';
else if (isRecord(choice)) body.tool_choice = flags.forcedChoice ? { type: 'function', function: { name: choice.name } } : 'auto';
} }
if (flags.temperature && req.temperature !== undefined && caps.temperature !== false) body.temperature = req.temperature; if (flags.temperature && req.temperature !== undefined && caps.temperature !== false) body.temperature = req.temperature;
if (flags.maxKey && req.maxOutputTokens) body[flags.maxKey] = req.maxOutputTokens; if (flags.maxKey && req.maxOutputTokens) body[flags.maxKey] = req.maxOutputTokens;
if (flags.reasoning && caps.reasoning === true && req.reasoningEffort && req.reasoningEffort !== 'none') body.reasoning_effort = req.reasoningEffort; if (flags.reasoning && caps.reasoning === true && req.reasoningEffort && req.reasoningEffort !== 'none') body.reasoning_effort = nearestEffort(req.reasoningEffort, COMPAT_EFFORTS);
if (flags.jsonMode && req.jsonMode) body.response_format = { type: 'json_object' }; if (flags.jsonMode && req.jsonMode) body.response_format = { type: 'json_object' };
if (o.adjustBody) {
o.adjustBody(body, req);
if (!flags.reasoning) delete body.reasoning_effort;
}
return body; return body;
} }
/** A 400 that says the model cannot do tool calling at all (not just a rejected parameter). */
const NO_TOOLS_RE = /(does not|doesn't|do not|cannot|can't|not) support(s|ed)? (tool|function)|(tool|function)[ _-]?(call(ing|s)?|use)? (is|are) not (supported|available|enabled)|unsupported.{0,20}(tool|function)|no tool support/;
function mapFinish(reason: string): StopReason { function mapFinish(reason: string): StopReason {
switch (reason) { switch (reason) {
case 'stop': case 'stop':
@ -160,14 +203,15 @@ export async function* streamChatCompletions(o: CompatOptions, req: ChatRequest)
const ctx = errorContext(o); const ctx = errorContext(o);
const base = normalizeCompatBase(o.baseUrl); const base = normalizeCompatBase(o.baseUrl);
const local = isLocalUrl(base); const local = isLocalUrl(base);
const flags: BodyFlags = { tools: true, usage: true, jsonMode: true, temperature: true, reasoning: true, maxKey: 'max_tokens' }; const flags: BodyFlags = { tools: true, forcedChoice: o.forcedToolChoice ? o.forcedToolChoice(req) : true, usage: true, jsonMode: true, temperature: true, reasoning: true, maxKey: 'max_tokens' };
const forcing = req.toolChoice === 'required' || isRecord(req.toolChoice);
let http: HttpResponse; let http: HttpResponse;
for (let attempt = 0; ; attempt += 1) { for (let attempt = 0; ; attempt += 1) {
http = await httpRequest(`${base}/chat/completions`, { http = await httpRequest(`${base}/chat/completions`, {
...ctx, ...ctx,
headers: authHeaders(o), headers: authHeaders(o),
body: buildBody(req, flags), body: buildBody(req, flags, o),
signal: req.signal, signal: req.signal,
// A local server may spend minutes loading a model into memory before the first byte. // A local server may spend minutes loading a model into memory before the first byte.
firstByteTimeoutMs: local ? 10 * 60_000 : undefined, firstByteTimeoutMs: local ? 10 * 60_000 : undefined,
@ -184,9 +228,12 @@ export async function* streamChatCompletions(o: CompatOptions, req: ChatRequest)
else if (flags.reasoning && /reasoning_effort|reasoning/.test(detail) && req.reasoningEffort) flags.reasoning = false; else if (flags.reasoning && /reasoning_effort|reasoning/.test(detail) && req.reasoningEffort) flags.reasoning = false;
else if (flags.temperature && /temperature/.test(detail)) flags.temperature = false; else if (flags.temperature && /temperature/.test(detail)) flags.temperature = false;
else if (flags.jsonMode && req.jsonMode && /response_format|json_object|json mode/.test(detail)) flags.jsonMode = false; else if (flags.jsonMode && req.jsonMode && /response_format|json_object|json mode/.test(detail)) flags.jsonMode = false;
else if (flags.tools && req.tools?.length && /tool|function/.test(detail)) { // A forced tool choice is often what is rejected (DeepSeek in thinking mode, some
// routers): keep the tools and ask for the call in the prompt instead.
else if (flags.forcedChoice && forcing && flags.tools && req.tools?.length && /tool_choice|tool choice|required|function_call|named/.test(detail)) flags.forcedChoice = false;
else if (flags.tools && req.tools?.length && NO_TOOLS_RE.test(detail)) {
// The model (or server) cannot do tool calling at all. // The model (or server) cannot do tool calling at all.
if (req.toolChoice === 'required' || isRecord(req.toolChoice)) { if (forcing) {
throw new AIError('unsupported', `${o.label} reports that "${req.model}" does not support tool calling. Pick a different model for this task.`, { throw new AIError('unsupported', `${o.label} reports that "${req.model}" does not support tool calling. Pick a different model for this task.`, {
status: err.status, status: err.status,
providerMessage: err.providerMessage, providerMessage: err.providerMessage,
@ -200,6 +247,7 @@ export async function* streamChatCompletions(o: CompatOptions, req: ChatRequest)
let text = ''; let text = '';
let finish = ''; let finish = '';
let reasoningSeen = false; let reasoningSeen = false;
let reasoningText = '';
const usage = { input: 0, output: 0, cacheRead: 0, reasoning: 0 }; const usage = { input: 0, output: 0, cacheRead: 0, reasoning: 0 };
const calls: { id: string; name: string; args: string }[] = []; const calls: { id: string; name: string; args: string }[] = [];
@ -211,6 +259,8 @@ export async function* streamChatCompletions(o: CompatOptions, req: ChatRequest)
usage.input = num(u.prompt_tokens) || usage.input; usage.input = num(u.prompt_tokens) || usage.input;
usage.output = num(u.completion_tokens) || usage.output; usage.output = num(u.completion_tokens) || usage.output;
if (isRecord(u.prompt_tokens_details)) usage.cacheRead = num(u.prompt_tokens_details.cached_tokens); if (isRecord(u.prompt_tokens_details)) usage.cacheRead = num(u.prompt_tokens_details.cached_tokens);
// DeepSeek's own field (the same number as cached_tokens where both are sent).
if (!usage.cacheRead && num(u.prompt_cache_hit_tokens)) usage.cacheRead = num(u.prompt_cache_hit_tokens);
if (isRecord(u.completion_tokens_details)) usage.reasoning = num(u.completion_tokens_details.reasoning_tokens); if (isRecord(u.completion_tokens_details)) usage.reasoning = num(u.completion_tokens_details.reasoning_tokens);
} }
const choice = Array.isArray(data.choices) ? data.choices[0] : undefined; const choice = Array.isArray(data.choices) ? data.choices[0] : undefined;
@ -222,6 +272,7 @@ export async function* streamChatCompletions(o: CompatOptions, req: ChatRequest)
const reasoning = str(delta.reasoning_content) || str(delta.reasoning) || str(delta.thinking); const reasoning = str(delta.reasoning_content) || str(delta.reasoning) || str(delta.thinking);
if (reasoning) { if (reasoning) {
reasoningSeen = true; reasoningSeen = true;
if (o.replayReasoning) reasoningText += reasoning;
yield { type: 'reasoning', delta: reasoning }; yield { type: 'reasoning', delta: reasoning };
} }
const piece = typeof delta.content === 'string' ? delta.content : ''; const piece = typeof delta.content === 'string' ? delta.content : '';
@ -270,6 +321,7 @@ export async function* streamChatCompletions(o: CompatOptions, req: ChatRequest)
throw new AIError('invalid_response', `${o.label} returned an empty response.`, { retryable: true }); throw new AIError('invalid_response', `${o.label} returned an empty response.`, { retryable: true });
} }
const message: ChatMessage = { role: 'assistant', content }; const message: ChatMessage = { role: 'assistant', content };
if (o.replayReasoning) message.providerData = { kind: o.kind, data: { reasoning_content: reasoningText } };
yield { yield {
type: 'done', type: 'done',
message, message,

View file

@ -6,7 +6,9 @@
import { afterEach, describe, expect, it, vi } from 'vitest'; import { afterEach, describe, expect, it, vi } from 'vitest';
import { AIError, type ChatMessage, type ChatRequest, type ProviderAdapter, type ProviderConfig, type ProviderKind, type StreamEvent, type ToolDef, type Usage } from '../types.ts'; import { AIError, type ChatMessage, type ChatRequest, type ProviderAdapter, type ProviderConfig, type ProviderKind, type StreamEvent, type ToolDef, type Usage } from '../types.ts';
import { anthropicAdapter } from './anthropic.ts'; import { anthropicAdapter } from './anthropic.ts';
import { lookupModelDefaults } from './catalog.ts'; import { cachedInputPrice, lookupModelDefaults, priceMultiplier } from './catalog.ts';
import { nearestEffort } from './common.ts';
import { deepseekAdapter } from './deepseek.ts';
import { toGeminiSchema, geminiAdapter } from './gemini.ts'; import { toGeminiSchema, geminiAdapter } from './gemini.ts';
import { parseSSE } from './http.ts'; import { parseSSE } from './http.ts';
import { ollamaAdapter } from './ollama.ts'; import { ollamaAdapter } from './ollama.ts';
@ -751,6 +753,139 @@ describe('openai-compatible stream_options fallback', () => {
}); });
}); });
/** A Chat Completions stream that calls one tool, with optional reasoning text first. */
function compatToolStream(name: string, args: string, reasoning?: string): string[] {
return [
...(reasoning ? [ev({ choices: [{ index: 0, delta: { reasoning_content: reasoning } }] })] : []),
ev({ choices: [{ index: 0, delta: { tool_calls: [{ index: 0, id: 'call_9', type: 'function', function: { name, arguments: args } }] } }] }),
ev({ choices: [{ index: 0, delta: {}, finish_reason: 'tool_calls' }], usage: { prompt_tokens: 100, completion_tokens: 5, prompt_cache_hit_tokens: 60 } }),
DONE,
];
}
describe('openai-compatible forced tool choice', () => {
it('asks for the call in the prompt when a forced tool_choice is rejected, instead of reporting no tool support', async () => {
stubFetch(
queue(
() => jsonResponse({ error: { message: 'deepseek-flash does not support this tool_choice in thinking mode', type: 'invalid_request_error' } }, 400),
() => sseResponse(compatToolStream('lookup', '{"q":"cats"}')),
),
);
const { done } = await run(compatKit.adapter, compatKit.cfg, { model: 'some-model', messages: [user('hi')], tools: [TOOL], toolChoice: { name: 'lookup' } });
expect(calls).toHaveLength(2);
expect(calls[0]!.body.tool_choice).toEqual({ type: 'function', function: { name: 'lookup' } });
expect(calls[1]!.body.tool_choice).toBe('auto');
expect(calls[1]!.body.tools).toHaveLength(1);
expect(calls[1]!.body.messages[0].content).toContain('must call the `lookup` tool');
expect(done.message.content).toEqual([{ type: 'tool_call', id: 'call_9', name: 'lookup', input: { q: 'cats' } }]);
});
it('only reports "unsupported" when the server says tools are not supported at all', async () => {
stubFetch(queue(() => jsonResponse({ error: { message: 'This model does not support tools.' } }, 400)));
const err = await failure(run(compatKit.adapter, compatKit.cfg, { model: 'tiny', messages: [user('hi')], tools: [TOOL], toolChoice: 'required' }));
expect(err.code).toBe('unsupported');
});
it('does not mistake an unrelated 400 that mentions tools for missing tool support', async () => {
stubFetch(queue(() => jsonResponse({ error: { message: "Messages with role 'tool' must be a response to a preceding message with 'tool_calls'." } }, 400)));
const err = await failure(run(compatKit.adapter, compatKit.cfg, { model: 'm', messages: [user('hi')], tools: [TOOL], toolChoice: 'required' }));
expect(err.code).not.toBe('unsupported');
});
});
describe('deepseek adapter', () => {
const cfg = cfgOf('deepseek', 'sk-test-key-123456');
it('keeps thinking on for forced tool calls and asks for the call in the prompt instead', async () => {
stubFetch(queue(() => sseResponse(compatToolStream('lookup', '{"q":"x"}'))));
const { done } = await run(deepseekAdapter, cfg, { model: 'deepseek-flash', system: 'Base', messages: [user('hi')], tools: [TOOL], toolChoice: { name: 'lookup' }, reasoningEffort: 'high', capabilities: { reasoning: true, tools: true } });
expect(calls[0]!.url).toBe('https://api.deepseek.com/v1/chat/completions');
expect(calls[0]!.headers.Authorization).toBe('Bearer sk-test-key-123456');
expect(calls[0]!.body.thinking).toEqual({ type: 'enabled' });
expect(calls[0]!.body.reasoning_effort).toBe('high');
expect(calls[0]!.body.tool_choice).toBe('auto');
expect(calls[0]!.body.messages[0].content).toMatch(/^Base\n\nFor this turn you must call the `lookup` tool/);
expect(done.message.content[0]).toMatchObject({ type: 'tool_call', name: 'lookup' });
});
it('forces the tool choice only with thinking off (effort "none")', async () => {
stubFetch(queue(() => sseResponse(compatToolStream('lookup', '{"q":"x"}'))));
await run(deepseekAdapter, cfg, { model: 'deepseek-flash', messages: [user('hi')], tools: [TOOL], toolChoice: { name: 'lookup' }, reasoningEffort: 'none', capabilities: { reasoning: true, tools: true } });
expect(calls[0]!.body.thinking).toEqual({ type: 'disabled' });
expect(calls[0]!.body.reasoning_effort).toBeUndefined();
expect(calls[0]!.body.tool_choice).toEqual({ type: 'function', function: { name: 'lookup' } });
});
it('maps effort levels onto low / high / max and keeps thinking on', async () => {
for (const [effort, expected] of [['minimal', 'low'], ['medium', 'high'], ['xhigh', 'max'], ['max', 'max']] as const) {
stubFetch(queue(() => sseResponse(compatKit.text(['ok']))));
await run(deepseekAdapter, cfg, { model: 'deepseek-flash', messages: [user('hi')], reasoningEffort: effort, capabilities: { reasoning: true }, temperature: 0.3 });
expect(calls[0]!.body.thinking).toEqual({ type: 'enabled' });
expect(calls[0]!.body.reasoning_effort).toBe(expected);
expect(calls[0]!.body.temperature).toBeUndefined();
}
stubFetch(queue(() => sseResponse(compatKit.text(['ok']))));
await run(deepseekAdapter, cfg, { model: 'deepseek-flash', messages: [user('hi')], reasoningEffort: 'none', capabilities: { reasoning: true } });
expect(calls[0]!.body.thinking).toEqual({ type: 'disabled' });
});
it('keeps reasoning_content and replays it on the next request, with an empty string for other providers', async () => {
stubFetch(queue(() => sseResponse(compatToolStream('lookup', '{"q":"cats"}', 'Let me look that up.'))));
const first = await run(deepseekAdapter, cfg, { model: 'deepseek-flash', messages: [user('hi')], tools: [TOOL], toolChoice: 'auto' });
expect(first.done.message.providerData).toEqual({ kind: 'deepseek', data: { reasoning_content: 'Let me look that up.' } });
expect(first.done.usage).toMatchObject({ inputTokens: 100, cacheReadTokens: 60 });
stubFetch(queue(() => sseResponse(compatKit.text(['done']))));
const foreign = toolCallMsg({ providerData: { kind: 'openai', data: { x: 1 } } });
await run(deepseekAdapter, cfg, { model: 'deepseek-flash', messages: [user('hi'), first.done.message, toolResultMsg, user('again'), foreign, toolResultMsg], tools: [TOOL], toolChoice: 'auto' });
const assistants = calls[0]!.body.messages.filter((m: any) => m.role === 'assistant');
expect(assistants[0].reasoning_content).toBe('Let me look that up.');
expect(assistants[1].reasoning_content).toBe('');
});
it('lists models with limits, vision and reasoning from /models', async () => {
stubFetch(
queue(() =>
jsonResponse({
data: [
{ id: 'deepseek-flash', name: 'DeepSeek-V4.1-Flash', context_window: 1048576, max_output_tokens: 393216, input_modalities: ['text', 'image'], effort: { supported_levels: ['low', 'high', 'max'] } },
{ id: 'deepseek-v4-pro', name: 'DeepSeek-V4-Pro', context_window: 1048576, max_output_tokens: 393216, input_modalities: ['text'], effort: { supported_levels: ['low', 'high', 'max'] } },
],
}),
),
);
const models = await deepseekAdapter.listModels(cfg);
expect(calls[0]!.url).toBe('https://api.deepseek.com/models');
const flash = models.find((m) => m.id === 'deepseek-flash')!;
expect(flash).toMatchObject({ contextWindow: 1048576, maxOutput: 393216, priceIn: 0.3, priceCachedIn: 0.006, priceOut: 1.2 });
expect(flash.capabilities).toMatchObject({ tools: true, vision: true, reasoning: true });
expect(models.find((m) => m.id === 'deepseek-v4-pro')!.capabilities?.vision).toBe(false);
});
});
describe('reasoning effort and cache pricing helpers', () => {
it('maps efforts to the nearest supported level, rounding ties up', () => {
expect(nearestEffort('medium', ['low', 'high', 'max'] as const)).toBe('high');
expect(nearestEffort('minimal', ['low', 'high', 'max'] as const)).toBe('low');
expect(nearestEffort('xhigh', ['minimal', 'low', 'medium', 'high'] as const)).toBe('high');
expect(nearestEffort('max', ['low', 'medium', 'high', 'xhigh', 'max'] as const)).toBe('max');
});
it('uses a model cached price when set and the provider discount otherwise', () => {
expect(cachedInputPrice('deepseek', 'deepseek-flash', 0.3, 0.006)).toBe(0.006);
expect(cachedInputPrice('anthropic', 'claude-sonnet-5-5', 2, null)).toBeCloseTo(0.2);
expect(cachedInputPrice('openai', 'gpt-4o', 2.5, null)).toBeCloseTo(1.25);
expect(cachedInputPrice('openai_compatible', 'x', 1, null)).toBe(1);
});
it('halves DeepSeek prices outside peak hours only', () => {
expect(priceMultiplier('deepseek', Date.UTC(2026, 10, 16, 2, 30))).toBe(1); // Monday 02:30 UTC
expect(priceMultiplier('deepseek', Date.UTC(2026, 10, 16, 12, 0))).toBe(0.5); // Monday noon
expect(priceMultiplier('deepseek', Date.UTC(2026, 10, 15, 2, 30))).toBe(0.5); // Sunday
expect(priceMultiplier('openai', Date.UTC(2026, 10, 16, 12, 0))).toBe(1);
});
});
describe('openai-compatible listModels', () => { describe('openai-compatible listModels', () => {
it('parses OpenRouter-style metadata, filters embeddings and merges vendor catalog defaults', async () => { it('parses OpenRouter-style metadata, filters embeddings and merges vendor catalog defaults', async () => {
stubFetch( stubFetch(

View file

@ -10,11 +10,12 @@ import type { DB } from '../db.ts';
import { HttpError, notFound, type AppContext } from '../http.ts'; import { HttpError, notFound, type AppContext } from '../http.ts';
import { getSetting, setSetting } from '../settings.ts'; import { getSetting, setSetting } from '../settings.ts';
import { newId, now, parseJson } from '../util.ts'; import { newId, now, parseJson } from '../util.ts';
import { getAdapter, lookupModelDefaults } from './providers/index.ts'; import { cachedInputPrice, cacheWriteRatio, getAdapter, lookupModelDefaults, priceMultiplier } from './providers/index.ts';
import { import {
AIError, AIError,
DEFAULT_CAPABILITIES, DEFAULT_CAPABILITIES,
PROVIDER_KINDS, PROVIDER_KINDS,
REASONING_EFFORTS,
type ChatMessage, type ChatMessage,
type ChatRequest, type ChatRequest,
type DiscoveredModel, type DiscoveredModel,
@ -57,6 +58,7 @@ interface ModelRow {
max_output: number | null; max_output: number | null;
price_in: number | null; price_in: number | null;
price_out: number | null; price_out: number | null;
price_cached_in: number | null;
} }
export const TASKS = ['chat', 'generate', 'vision', 'quick'] as const; export const TASKS = ['chat', 'generate', 'vision', 'quick'] as const;
@ -82,7 +84,7 @@ const EMPTY_TASK: TaskConfig = { modelId: null, temperature: null, reasoningEffo
export const taskConfigSchema = z.object({ export const taskConfigSchema = z.object({
modelId: z.string().nullable(), modelId: z.string().nullable(),
temperature: z.number().min(0).max(2).nullable(), temperature: z.number().min(0).max(2).nullable(),
reasoningEffort: z.enum(['none', 'low', 'medium', 'high']).nullable(), reasoningEffort: z.enum(REASONING_EFFORTS).nullable(),
maxOutputTokens: z.number().int().min(256).max(200000).nullable(), maxOutputTokens: z.number().int().min(256).max(200000).nullable(),
}); });
@ -122,6 +124,8 @@ function mapModel(row: ModelRow & { provider_name?: string; provider_kind?: stri
maxOutput: row.max_output, maxOutput: row.max_output,
priceIn: row.price_in, priceIn: row.price_in,
priceOut: row.price_out, priceOut: row.price_out,
/** Null = not set; costs then use the provider's usual cache discount. */
priceCachedIn: row.price_cached_in,
}; };
} }
export type ModelDto = ReturnType<typeof mapModel>; export type ModelDto = ReturnType<typeof mapModel>;
@ -249,11 +253,12 @@ export async function discoverModels(app: AppContext, id: string): Promise<{ add
if (current) { if (current) {
// Refresh facts the provider reports, but never overwrite prices or flags the user may have edited. // Refresh facts the provider reports, but never overwrite prices or flags the user may have edited.
app.db.run( app.db.run(
'UPDATE ai_models SET context_window = COALESCE(?, context_window), max_output = COALESCE(?, max_output), price_in = COALESCE(price_in, ?), price_out = COALESCE(price_out, ?), updated_at = ? WHERE id = ?', 'UPDATE ai_models SET context_window = COALESCE(?, context_window), max_output = COALESCE(?, max_output), price_in = COALESCE(price_in, ?), price_out = COALESCE(price_out, ?), price_cached_in = COALESCE(price_cached_in, ?), updated_at = ? WHERE id = ?',
m.contextWindow ?? null, m.contextWindow ?? null,
m.maxOutput ?? null, m.maxOutput ?? null,
m.priceIn ?? null, m.priceIn ?? null,
m.priceOut ?? null, m.priceOut ?? null,
m.priceCachedIn ?? null,
at, at,
current.id, current.id,
); );
@ -270,8 +275,8 @@ function insertModel(db: DB, providerId: string, m: DiscoveredModel, source: str
const id = newId(); const id = newId();
const at = now(); const at = now();
db.run( db.run(
`INSERT INTO ai_models (id, provider_id, model, label, source, enabled, capabilities, context_window, max_output, price_in, price_out, created_at, updated_at) `INSERT INTO ai_models (id, provider_id, model, label, source, enabled, capabilities, context_window, max_output, price_in, price_out, price_cached_in, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
id, id,
providerId, providerId,
m.id, m.id,
@ -283,6 +288,7 @@ function insertModel(db: DB, providerId: string, m: DiscoveredModel, source: str
m.maxOutput ?? null, m.maxOutput ?? null,
m.priceIn ?? null, m.priceIn ?? null,
m.priceOut ?? null, m.priceOut ?? null,
m.priceCachedIn ?? null,
at, at,
at, at,
); );
@ -331,6 +337,7 @@ export const modelPatchSchema = z.object({
maxOutput: z.number().int().min(16).max(10_000_000).nullable().optional(), maxOutput: z.number().int().min(16).max(10_000_000).nullable().optional(),
priceIn: z.number().min(0).max(100000).nullable().optional(), priceIn: z.number().min(0).max(100000).nullable().optional(),
priceOut: z.number().min(0).max(100000).nullable().optional(), priceOut: z.number().min(0).max(100000).nullable().optional(),
priceCachedIn: z.number().min(0).max(100000).nullable().optional(),
}); });
export function patchModel(db: DB, id: string, input: z.input<typeof modelPatchSchema>): ModelDto { export function patchModel(db: DB, id: string, input: z.input<typeof modelPatchSchema>): ModelDto {
@ -339,7 +346,7 @@ export function patchModel(db: DB, id: string, input: z.input<typeof modelPatchS
if (!row) throw notFound('Model'); if (!row) throw notFound('Model');
const caps = { ...parseJson<Partial<ModelCapabilities>>(row.capabilities, {}), ...patch.capabilities }; const caps = { ...parseJson<Partial<ModelCapabilities>>(row.capabilities, {}), ...patch.capabilities };
db.run( db.run(
'UPDATE ai_models SET enabled = ?, label = ?, capabilities = ?, context_window = ?, max_output = ?, price_in = ?, price_out = ?, updated_at = ? WHERE id = ?', 'UPDATE ai_models SET enabled = ?, label = ?, capabilities = ?, context_window = ?, max_output = ?, price_in = ?, price_out = ?, price_cached_in = ?, updated_at = ? WHERE id = ?',
patch.enabled === undefined ? row.enabled : patch.enabled ? 1 : 0, patch.enabled === undefined ? row.enabled : patch.enabled ? 1 : 0,
patch.label ?? row.label, patch.label ?? row.label,
JSON.stringify(caps), JSON.stringify(caps),
@ -347,6 +354,7 @@ export function patchModel(db: DB, id: string, input: z.input<typeof modelPatchS
patch.maxOutput === undefined ? row.max_output : patch.maxOutput, patch.maxOutput === undefined ? row.max_output : patch.maxOutput,
patch.priceIn === undefined ? row.price_in : patch.priceIn, patch.priceIn === undefined ? row.price_in : patch.priceIn,
patch.priceOut === undefined ? row.price_out : patch.priceOut, patch.priceOut === undefined ? row.price_out : patch.priceOut,
patch.priceCachedIn === undefined ? row.price_cached_in : patch.priceCachedIn,
now(), now(),
id, id,
); );
@ -423,19 +431,33 @@ export function resolveModel(app: AppContext, task: TaskName, overrideModelId?:
/* ------------------------------ usage ------------------------------ */ /* ------------------------------ usage ------------------------------ */
export function estimateCost(model: Pick<ModelDto, 'priceIn' | 'priceOut'>, usage: Usage): number | null { /**
* Estimated USD cost of one call. Input tokens are split into fresh, cache-hit and
* cache-write tokens, each at its own rate: the model's cached price when set, otherwise
* the provider's published cache discount; Claude's cache writes cost 1.25x. Providers
* with time-of-day pricing (DeepSeek off-peak) are adjusted for when the call was made.
*/
export function estimateCost(
model: Pick<ModelDto, 'priceIn' | 'priceOut' | 'model'> & { priceCachedIn?: number | null; providerKind?: ProviderKind | '' },
usage: Usage,
at: number = Date.now(),
): number | null {
if (model.priceIn === null && model.priceOut === null) return null; if (model.priceIn === null && model.priceOut === null) return null;
// Cached input is billed at a fraction of the list price by every provider; 10% is a close, conservative stand-in. const kind = (model.providerKind || 'openai_compatible') as ProviderKind;
const cached = usage.cacheReadTokens ?? 0; const priceIn = model.priceIn ?? 0;
const fresh = Math.max(0, usage.inputTokens - cached); const cachedRate = cachedInputPrice(kind, model.model, model.priceIn, model.priceCachedIn ?? null);
return ((fresh + cached * 0.1) * (model.priceIn ?? 0) + usage.outputTokens * (model.priceOut ?? 0)) / 1_000_000; const cached = Math.min(usage.inputTokens, usage.cacheReadTokens ?? 0);
const written = Math.min(usage.inputTokens - cached, usage.cacheWriteTokens ?? 0);
const fresh = Math.max(0, usage.inputTokens - cached - written);
const input = fresh * priceIn + cached * cachedRate + written * priceIn * cacheWriteRatio(kind);
return ((input + usage.outputTokens * (model.priceOut ?? 0)) * priceMultiplier(kind, at)) / 1_000_000;
} }
function recordUsage(app: AppContext, r: ResolvedModel, task: string, usage: Usage | null, started: number, error?: string): void { function recordUsage(app: AppContext, r: ResolvedModel, task: string, usage: Usage | null, started: number, error?: string): void {
try { try {
app.db.run( app.db.run(
`INSERT INTO ai_usage (at, provider_id, provider_name, model, task, input_tokens, output_tokens, cache_read_tokens, cost, ok, error, duration_ms) `INSERT INTO ai_usage (at, provider_id, provider_name, model, task, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost, ok, error, duration_ms)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
now(), now(),
r.provider.id, r.provider.id,
r.provider.name, r.provider.name,
@ -444,6 +466,7 @@ function recordUsage(app: AppContext, r: ResolvedModel, task: string, usage: Usa
usage?.inputTokens ?? 0, usage?.inputTokens ?? 0,
usage?.outputTokens ?? 0, usage?.outputTokens ?? 0,
usage?.cacheReadTokens ?? 0, usage?.cacheReadTokens ?? 0,
usage?.cacheWriteTokens ?? 0,
usage ? estimateCost(r.model, usage) : null, usage ? estimateCost(r.model, usage) : null,
error ? 0 : 1, error ? 0 : 1,
(error ?? '').slice(0, 300), (error ?? '').slice(0, 300),
@ -597,7 +620,7 @@ export async function generateStructured(app: AppContext, opts: StructuredOption
export function usageSummary(db: DB, days: number) { export function usageSummary(db: DB, days: number) {
const since = now() - days * 86_400_000; const since = now() - days * 86_400_000;
const byModel = db.all<Record<string, any>>( const byModel = db.all<Record<string, any>>(
`SELECT provider_name AS provider, model, COUNT(*) AS calls, SUM(input_tokens) AS input, SUM(output_tokens) AS output, SUM(cost) AS cost, `SELECT provider_name AS provider, model, COUNT(*) AS calls, SUM(input_tokens) AS input, SUM(cache_read_tokens) AS cached, SUM(output_tokens) AS output, SUM(cost) AS cost,
SUM(CASE WHEN ok = 0 THEN 1 ELSE 0 END) AS errors, SUM(CASE WHEN cost IS NULL AND ok = 1 THEN 1 ELSE 0 END) AS unpriced SUM(CASE WHEN ok = 0 THEN 1 ELSE 0 END) AS errors, SUM(CASE WHEN cost IS NULL AND ok = 1 THEN 1 ELSE 0 END) AS unpriced
FROM ai_usage WHERE at >= ? GROUP BY provider_name, model ORDER BY cost DESC, calls DESC`, FROM ai_usage WHERE at >= ? GROUP BY provider_name, model ORDER BY cost DESC, calls DESC`,
since, since,
@ -607,7 +630,7 @@ export function usageSummary(db: DB, days: number) {
since, since,
); );
const total = db.get<Record<string, any>>( const total = db.get<Record<string, any>>(
`SELECT COUNT(*) AS calls, COALESCE(SUM(input_tokens), 0) AS input, COALESCE(SUM(output_tokens), 0) AS output, COALESCE(SUM(cost), 0) AS cost FROM ai_usage WHERE at >= ?`, `SELECT COUNT(*) AS calls, COALESCE(SUM(input_tokens), 0) AS input, COALESCE(SUM(cache_read_tokens), 0) AS cached, COALESCE(SUM(output_tokens), 0) AS output, COALESCE(SUM(cost), 0) AS cost FROM ai_usage WHERE at >= ?`,
since, since,
)!; )!;
const recentErrors = db.all<Record<string, any>>(`SELECT at, provider_name AS provider, model, task, error FROM ai_usage WHERE ok = 0 AND at >= ? ORDER BY at DESC LIMIT 10`, since); const recentErrors = db.all<Record<string, any>>(`SELECT at, provider_name AS provider, model, task, error FROM ai_usage WHERE ok = 0 AND at >= ? ORDER BY at DESC LIMIT 10`, since);

View file

@ -6,9 +6,9 @@
* `server/ai/providers/` may depend on a provider-specific request or response. * `server/ai/providers/` may depend on a provider-specific request or response.
*/ */
export type ProviderKind = 'openai' | 'anthropic' | 'gemini' | 'openai_compatible' | 'ollama'; export type ProviderKind = 'openai' | 'anthropic' | 'gemini' | 'deepseek' | 'openai_compatible' | 'ollama';
export const PROVIDER_KINDS: ProviderKind[] = ['openai', 'anthropic', 'gemini', 'openai_compatible', 'ollama']; export const PROVIDER_KINDS: ProviderKind[] = ['openai', 'anthropic', 'gemini', 'deepseek', 'openai_compatible', 'ollama'];
/** Decrypted provider connection, only ever held server-side. */ /** Decrypted provider connection, only ever held server-side. */
export interface ProviderConfig { export interface ProviderConfig {
@ -51,7 +51,12 @@ export interface ToolDef {
parameters: Record<string, unknown>; parameters: Record<string, unknown>;
} }
export type ReasoningEffort = 'none' | 'low' | 'medium' | 'high'; /**
* Reasoning effort, from "off" to the most a provider offers. Adapters map each level onto
* the nearest value their API accepts (see `nearestEffort`).
*/
export const REASONING_EFFORTS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const;
export type ReasoningEffort = (typeof REASONING_EFFORTS)[number];
export interface ModelCapabilities { export interface ModelCapabilities {
tools: boolean; tools: boolean;
@ -108,6 +113,8 @@ export interface DiscoveredModel {
/** USD per million tokens, when known. */ /** USD per million tokens, when known. */
priceIn?: number; priceIn?: number;
priceOut?: number; priceOut?: number;
/** USD per million cached (cache-hit) input tokens, when the provider prices them separately. */
priceCachedIn?: number;
} }
export interface TestResult { export interface TestResult {

View file

@ -1,4 +1,5 @@
import fs from 'node:fs'; import fs from 'node:fs';
import { setLocalEmbeddingDefault } from './services/semantic.ts';
import path from 'node:path'; import path from 'node:path';
import { Hono } from 'hono'; import { Hono } from 'hono';
import { compress } from 'hono/compress'; import { compress } from 'hono/compress';
@ -50,6 +51,7 @@ const AI_STATUS: Partial<Record<AIError['code'], number>> = { not_configured: 40
export function createApp(app: AppContext): Hono { export function createApp(app: AppContext): Hono {
const hono = new Hono(); const hono = new Hono();
setLocalEmbeddingDefault(app.config.localEmbeddings);
hono.onError((err, c) => { hono.onError((err, c) => {
if (err instanceof HttpError) { if (err instanceof HttpError) {

View file

@ -23,6 +23,11 @@ export interface Config {
maxUploadBytes: number; maxUploadBytes: number;
backupKeep: number; backupKeep: number;
timezone: string; timezone: string;
/**
* Use the built-in embedding model for semantic search when no embedding provider has been
* chosen. On by default; off in tests. LOCAL_EMBEDDINGS=off disables it.
*/
localEmbeddings: boolean;
} }
function bool(v: string | undefined, fallback: boolean): boolean { function bool(v: string | undefined, fallback: boolean): boolean {
@ -89,6 +94,7 @@ export function loadConfig(overrides: Partial<Config> = {}, envVars: NodeJS.Proc
maxUploadBytes: Math.max(1, Number(envVars.MAX_UPLOAD_MB ?? 100)) * 1024 * 1024, maxUploadBytes: Math.max(1, Number(envVars.MAX_UPLOAD_MB ?? 100)) * 1024 * 1024,
backupKeep: Math.max(1, Number(envVars.BACKUP_KEEP ?? 7)), backupKeep: Math.max(1, Number(envVars.BACKUP_KEEP ?? 7)),
timezone, timezone,
localEmbeddings: bool(envVars.LOCAL_EMBEDDINGS, env !== 'test'),
...overrides, ...overrides,
}; };
} }

View file

@ -380,7 +380,38 @@ CREATE TABLE chunk_vectors (
CREATE INDEX chunk_vectors_model ON chunk_vectors(model_key); CREATE INDEX chunk_vectors_model ON chunk_vectors(model_key);
`; `;
/**
* Revision 1:
* - cached-input prices per model and cache-write token counts, for accurate cost estimates;
* - numeric-answer questions ("enter the dose"). SQLite cannot alter a CHECK constraint, so
* the questions table is rebuilt (nothing references it with a foreign key).
*/
const revision1 = `
ALTER TABLE ai_models ADD COLUMN price_cached_in REAL;
ALTER TABLE ai_usage ADD COLUMN cache_write_tokens INTEGER NOT NULL DEFAULT 0;
CREATE TABLE questions_new (
id TEXT PRIMARY KEY,
quiz_id TEXT NOT NULL REFERENCES quizzes(id) ON DELETE CASCADE,
type TEXT NOT NULL CHECK (type IN ('single','multi','numeric')),
stem TEXT NOT NULL,
options TEXT NOT NULL,
rationale TEXT NOT NULL DEFAULT '',
topic TEXT NOT NULL DEFAULT '',
difficulty TEXT NOT NULL DEFAULT 'medium',
tags TEXT NOT NULL DEFAULT '[]',
sort_order INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
INSERT INTO questions_new SELECT id, quiz_id, type, stem, options, rationale, topic, difficulty, tags, sort_order, created_at, updated_at FROM questions;
DROP TABLE questions;
ALTER TABLE questions_new RENAME TO questions;
CREATE INDEX questions_quiz ON questions(quiz_id, sort_order);
`;
export const MIGRATIONS: Migration[] = [ export const MIGRATIONS: Migration[] = [
{ id: 1, name: 'init', sql: init }, { id: 1, name: 'init', sql: init },
{ id: 2, name: 'embeddings', sql: embeddings }, { id: 2, name: 'embeddings', sql: embeddings },
{ id: 3, name: 'revision1', sql: revision1 },
]; ];

View file

@ -1,7 +1,7 @@
import { Hono, type Context } from 'hono'; import { Hono, type Context } from 'hono';
import { streamSSE } from 'hono/streaming'; import { streamSSE } from 'hono/streaming';
import { z } from 'zod'; 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 { import {
cancelGeneration, cancelGeneration,
createDraft, createDraft,
@ -10,6 +10,9 @@ import {
generateRequestSchema, generateRequestSchema,
getDraft, getDraft,
improveRequestSchema, improveRequestSchema,
instructionPatchSchema,
listInstructions,
saveInstruction,
listDrafts, listDrafts,
saveDraft, saveDraft,
startGeneration, startGeneration,
@ -39,7 +42,7 @@ import {
} from '../ai/service.ts'; } from '../ai/service.ts';
import { embedTexts, embeddingSettingsSchema, getEmbeddingSettings, embeddingStatus, rebuildIndex, saveEmbeddingSettings, scheduleIndexing } from '../services/semantic.ts'; import { embedTexts, embeddingSettingsSchema, getEmbeddingSettings, embeddingStatus, rebuildIndex, saveEmbeddingSettings, scheduleIndexing } from '../services/semantic.ts';
import { AIError } from '../ai/types.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; type Emit<T> = (event: T) => void;
@ -72,7 +75,7 @@ const contentDraftSchema = z.discriminatedUnion('kind', [
questions: z questions: z
.array( .array(
z.object({ z.object({
type: z.enum(['single', 'multi']), type: z.enum(['single', 'multi', 'numeric']),
stem: z.string().max(20000), 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), 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(''), rationale: z.string().max(20000).optional().default(''),
@ -103,6 +106,13 @@ export function aiRoutes(app: AppContext): Hono {
/* ------------------------------ configuration ------------------------------ */ /* ------------------------------ configuration ------------------------------ */
r.get('/ai/meta', (c) => c.json({ adapters: listAdapterMeta(), tasks: TASK_INFO, catalogUpdated: CATALOG_UPDATED })); 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/status', (c) => c.json(aiStatus(app)));
r.get('/ai/providers', (c) => c.json({ providers: listProviders(app) })); r.get('/ai/providers', (c) => c.json({ providers: listProviders(app) }));
@ -181,28 +191,63 @@ export function aiRoutes(app: AppContext): Hono {
/* ------------------------------ assistant ------------------------------ */ /* ------------------------------ 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) => { r.post('/ai/chat', async (c) => {
const body = await readBody(c, assistantRequestSchema); const body = await readBody(c, assistantRequestSchema);
return sse<AssistantEvent>(c, async (emit, signal) => { return sse<AssistantEvent>(c, async (emit, signal) => {
let conversationId: string;
try { try {
await runAssistantTurn(app, body, emit, signal); ({ conversationId } = startAssistantTurn(app, body));
} catch (err) { } 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; const ai = err instanceof AIError ? err : null;
if (!ai) app.log('error', 'Assistant request failed', err); const http = err instanceof HttpError ? err : null;
emit({ type: 'error', code: ai?.code ?? 'server', message: ai?.message ?? 'The assistant could not start.', detail: ai?.providerMessage }); 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: '' }); 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) => { r.get('/ai/conversations/:id', (c) => {
const id = idParam(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 }>('SELECT id, title, class_id FROM conversations WHERE id = ?', id);
if (!row) throw notFound('Conversation'); 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) => { r.delete('/ai/conversations/:id', (c) => {

View file

@ -10,7 +10,7 @@ import { badRequest, HttpError, idParam, readBody, type AppContext } from '../ht
import { appSettingsSchema, deleteSetting, getAppSettings, getSetting, setSetting } from '../settings.ts'; import { appSettingsSchema, deleteSetting, getAppSettings, getSetting, setSetting } from '../settings.ts';
import { createSnapshot, exportBundle, fullBackupStream, listBackups } from '../services/backup.ts'; import { createSnapshot, exportBundle, fullBackupStream, listBackups } from '../services/backup.ts';
import { createClass, createDeck, createFolder, createNote, createQuiz, draftCardToInput, draftQuestionToInput, getClass, getDeck, getQuiz, listCards, listQuestions } from '../services/content.ts'; import { createClass, createDeck, createFolder, createNote, createQuiz, draftCardToInput, draftQuestionToInput, getClass, getDeck, getQuiz, listCards, listQuestions } from '../services/content.ts';
import { createTemplate, deleteTemplate, listTemplates, templateInputSchema, updateTemplate } from '../services/templates.ts'; import { createTemplate, deleteTemplate, listTemplates, resetTemplate, templateInputSchema, updateTemplate } from '../services/templates.ts';
import { importV1 } from '../services/v1import.ts'; import { importV1 } from '../services/v1import.ts';
import { slugify } from '../util.ts'; import { slugify } from '../util.ts';
@ -92,6 +92,7 @@ export function dataRoutes(app: AppContext): Hono {
quiz: getSetting<string | null>(db, 'llm.quiz', null) ?? LLM_INSTRUCTIONS.quiz, quiz: getSetting<string | null>(db, 'llm.quiz', null) ?? LLM_INSTRUCTIONS.quiz,
deck: getSetting<string | null>(db, 'llm.deck', null) ?? LLM_INSTRUCTIONS.deck, deck: getSetting<string | null>(db, 'llm.deck', null) ?? LLM_INSTRUCTIONS.deck,
customized: { quiz: getSetting<string | null>(db, 'llm.quiz', null) !== null, deck: getSetting<string | null>(db, 'llm.deck', null) !== null }, customized: { quiz: getSetting<string | null>(db, 'llm.quiz', null) !== null, deck: getSetting<string | null>(db, 'llm.deck', null) !== null },
builtin: LLM_INSTRUCTIONS,
}), }),
); );
@ -258,6 +259,8 @@ export function dataRoutes(app: AppContext): Hono {
return c.json({ template: updateTemplate(db, idParam(c), body) }); return c.json({ template: updateTemplate(db, idParam(c), body) });
}); });
r.post('/templates/:id/reset', (c) => c.json({ template: resetTemplate(db, idParam(c)) }));
r.delete('/templates/:id', (c) => { r.delete('/templates/:id', (c) => {
deleteTemplate(db, idParam(c)); deleteTemplate(db, idParam(c));
return c.json({ ok: true }); return c.json({ ok: true });

View file

@ -157,7 +157,7 @@ function publicDocument(app: AppContext, id: string) {
return { kind: 'document' as const, id: doc.id as string, title: doc.title as string, filename: doc.filename as string, docKind: doc.kind as string, size: doc.size as number, pageCount: doc.page_count as number | null }; return { kind: 'document' as const, id: doc.id as string, title: doc.title as string, filename: doc.filename as string, docKind: doc.kind as string, size: doc.size as number, pageCount: doc.page_count as number | null };
} }
/** Quizzes, decks and notes inside a class or folder. Uploaded documents are never included in a collection share. */ /** Quizzes, decks, notes and processed documents inside a class or folder. */
function collectionItems(app: AppContext, share: ShareRow) { function collectionItems(app: AppContext, share: ShareRow) {
const { db } = app; const { db } = app;
const byFolder = share.kind === 'folder'; const byFolder = share.kind === 'folder';
@ -171,10 +171,13 @@ function collectionItems(app: AppContext, share: ShareRow) {
share.target_id, share.target_id,
); );
const notes = db.all<Record<string, any>>(`SELECT id, title, folder_id FROM notes WHERE ${where} ORDER BY sort_order, created_at`, share.target_id); const notes = db.all<Record<string, any>>(`SELECT id, title, folder_id FROM notes WHERE ${where} ORDER BY sort_order, created_at`, share.target_id);
// Documents are shared once they have been processed (a failed or half-read upload stays private).
const documents = db.all<Record<string, any>>(`SELECT id, title, folder_id, page_count, kind FROM documents WHERE ${where} AND status = 'ready' ORDER BY sort_order, created_at`, share.target_id);
return [ return [
...quizzes.filter((q) => q.n > 0).map((q) => ({ kind: 'quiz' as const, id: q.id as string, title: q.title as string, description: q.description as string, folderId: q.folder_id as string | null, count: q.n as number })), ...quizzes.filter((q) => q.n > 0).map((q) => ({ kind: 'quiz' as const, id: q.id as string, title: q.title as string, description: q.description as string, folderId: q.folder_id as string | null, count: q.n as number })),
...decks.filter((d) => d.n > 0).map((d) => ({ kind: 'deck' as const, id: d.id as string, title: d.title as string, description: d.description as string, folderId: d.folder_id as string | null, count: d.n as number })), ...decks.filter((d) => d.n > 0).map((d) => ({ kind: 'deck' as const, id: d.id as string, title: d.title as string, description: d.description as string, folderId: d.folder_id as string | null, count: d.n as number })),
...notes.map((n) => ({ kind: 'note' as const, id: n.id as string, title: n.title as string, description: '', folderId: n.folder_id as string | null, count: 0 })), ...notes.map((n) => ({ kind: 'note' as const, id: n.id as string, title: n.title as string, description: '', folderId: n.folder_id as string | null, count: 0 })),
...documents.map((d) => ({ kind: 'document' as const, id: d.id as string, title: d.title as string, description: String(d.kind ?? ''), folderId: d.folder_id as string | null, count: (d.page_count as number | null) ?? 0 })),
]; ];
} }
@ -232,14 +235,12 @@ export function publicRoutes(app: AppContext): Hono {
c.header('X-Robots-Tag', 'noindex, nofollow'); c.header('X-Robots-Tag', 'noindex, nofollow');
if (kind === 'quiz') return c.json(publicQuiz(app, id)); if (kind === 'quiz') return c.json(publicQuiz(app, id));
if (kind === 'deck') return c.json(publicDeck(app, id)); if (kind === 'deck') return c.json(publicDeck(app, id));
if (kind === 'document') return c.json(publicDocument(app, id));
return c.json(publicNote(app, id)); return c.json(publicNote(app, id));
}); });
/** Download for an explicitly shared document. */ const sendDocument = (documentId: string) => {
r.get('/:token/file', (c) => { const doc = db.get<{ filename: string; mime: string; storage_name: string }>('SELECT filename, mime, storage_name FROM documents WHERE id = ?', documentId);
const share = load(c.req.param('token'));
if (share.kind !== 'document') throw gone();
const doc = db.get<{ filename: string; mime: string; storage_name: string }>('SELECT filename, mime, storage_name FROM documents WHERE id = ?', share.target_id);
if (!doc) throw gone(); if (!doc) throw gone();
const file = path.join(app.config.uploadsDir, path.basename(doc.storage_name)); const file = path.join(app.config.uploadsDir, path.basename(doc.storage_name));
if (!fs.existsSync(file)) throw gone(); if (!fs.existsSync(file)) throw gone();
@ -254,6 +255,22 @@ export function publicRoutes(app: AppContext): Hono {
'X-Robots-Tag': 'noindex, nofollow', 'X-Robots-Tag': 'noindex, nofollow',
}, },
}); });
};
/** Download for an explicitly shared document. */
r.get('/:token/file', (c) => {
const share = load(c.req.param('token'));
if (share.kind !== 'document') throw gone();
return sendDocument(share.target_id);
});
/** Download for a document inside a shared class or folder. Membership is re-checked. */
r.get('/:token/items/document/:id/file', (c) => {
const share = load(c.req.param('token'));
if (share.kind !== 'class' && share.kind !== 'folder') throw gone();
const id = c.req.param('id');
if (!collectionItems(app, share).some((i) => i.kind === 'document' && i.id === id)) throw gone();
return sendDocument(id);
}); });
return r; return r;

View file

@ -363,7 +363,7 @@ export function getAttempt(db: DB, id: string): AttemptDto {
export const attemptPatchSchema = z.object({ export const attemptPatchSchema = z.object({
answers: z 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(), .optional(),
flags: z.array(z.string()).max(1000).optional(), flags: z.array(z.string()).max(1000).optional(),
currentIndex: z.number().int().min(0).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. // A checked practice answer is final: feedback has been shown.
if (prev?.checked && row.mode === 'practice') continue; if (prev?.checked && row.mode === 'practice') continue;
const valid = new Set(q.options.map((o) => o.id)); 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; const checked = row.mode === 'practice' && a.checked && selected.length > 0;
answers[qid] = { selected, checked, at }; answers[qid] = { selected, checked, at };
if (checked) recordResponse(db, row, q, selected, settings.sataScoring, 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. * ("why do patients on furosemide need bananas?") also find the right passage.
*/ */
import { z } from 'zod'; 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 { getAdapter } from '../ai/providers/index.ts';
import { providerConfigById } from '../ai/service.ts'; import { providerConfigById } from '../ai/service.ts';
import { AIError, type ProviderKind } from '../ai/types.ts'; import { AIError, type ProviderKind } from '../ai/types.ts';
@ -23,6 +24,7 @@ import { chunkById, searchChunks, type ChunkHit, type ChunkScope } from './docum
/* ------------------------------ settings ------------------------------ */ /* ------------------------------ settings ------------------------------ */
export interface EmbeddingSettings { export interface EmbeddingSettings {
/** A provider id, `local` for the built-in model, or null for keyword search only. */
providerId: string | null; providerId: string | null;
model: string; model: string;
/** Requested vector size for models that support shortening (OpenAI v3, Gemini). Null = native. */ /** 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 SETTINGS_KEY = 'embeddings';
const EMPTY: EmbeddingSettings = { providerId: null, model: '', dimensions: null }; 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. */ /** Suggested embedding model per provider type. Anthropic has no embeddings API. */
export const DEFAULT_EMBEDDING_MODELS: Record<ProviderKind, string | null> = { 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', ollama: 'nomic-embed-text',
openai_compatible: '', openai_compatible: '',
anthropic: null, anthropic: null,
deepseek: null,
}; };
/** USD per million input tokens, for the usage log. */ /** USD per million input tokens, for the usage log. */
@ -56,7 +66,11 @@ export const embeddingSettingsSchema = z.object({
}); });
export function getEmbeddingSettings(db: DB): EmbeddingSettings { 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'}`; 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 { export function saveEmbeddingSettings(app: AppContext, input: z.input<typeof embeddingSettingsSchema>): EmbeddingSettings {
const next = embeddingSettingsSchema.parse(input); 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); 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 (!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.'); 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[]> { export async function embedTexts(app: AppContext, texts: string[], purpose: 'document' | 'query', signal?: AbortSignal): Promise<Float32Array[]> {
const s = getEmbeddingSettings(app.db); 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 (!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 { cfg, kind, name } = providerConfigById(app, s.providerId!);
const adapter = getAdapter(kind); const adapter = getAdapter(kind);
if (!adapter.embed) throw new AIError('unsupported', `${name} has no embeddings API.`); 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 s = getEmbeddingSettings(app.db);
const total = app.db.get<{ n: number }>('SELECT COUNT(*) AS n FROM chunks')?.n ?? 0; 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; 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 ------------------------------ */ /* ------------------------------ vector search ------------------------------ */

View file

@ -2,7 +2,8 @@
* Reusable templates. * Reusable templates.
* - quiz / deck: a content skeleton (or a full copy of an existing item) to start from. * - quiz / deck: a content skeleton (or a full copy of an existing item) to start from.
* - generation: a saved set of AI generation options. * - 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 { z } from 'zod';
import type { DB } from '../db.ts'; import type { DB } from '../db.ts';
@ -33,7 +34,9 @@ const mapTemplate = (r: TemplateRow) => ({
name: r.name, name: r.name,
description: r.description, description: r.description,
payload: parseJson<Record<string, unknown>>(r.payload, {}), 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, updatedAt: r.updated_at,
}); });
@ -177,11 +180,12 @@ export function seedTemplates(db: DB): void {
const at = now(); const at = now();
db.tx(() => { db.tx(() => {
const keep = BUILTIN.map((t) => t.id); 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) { for (const t of BUILTIN) {
db.run( db.run(
`INSERT INTO templates (id, kind, name, description, payload, builtin, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 1, ?, ?) `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.id,
t.kind, t.kind,
t.name, 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> }) { 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'); if (!row) throw notFound('Template');
db.run( 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.name?.trim().slice(0, 120) || row.name,
input.description ?? row.description, input.description ?? row.description,
input.payload ? JSON.stringify(input.payload) : row.payload, input.payload ? JSON.stringify(input.payload) : row.payload,
row.builtin > 0 ? 2 : 0,
now(), now(),
id, id,
); );
return mapTemplate(db.get<TemplateRow>('SELECT * FROM templates WHERE id = ?', 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 { export function deleteTemplate(db: DB, id: string): void {
const { changes } = db.run('DELETE FROM templates WHERE id = ? AND builtin = 0', id); const { changes } = db.run('DELETE FROM templates WHERE id = ? AND builtin = 0', id);
if (!changes) throw notFound('Template'); if (!changes) throw notFound('Template');

View file

@ -19,7 +19,7 @@ export const LIMITS = {
noteContent: 400000, noteContent: 400000,
} as const; } as const;
export const QUESTION_TYPES = ['single', 'multi'] as const; export const QUESTION_TYPES = ['single', 'multi', 'numeric'] as const;
export type QuestionType = (typeof QUESTION_TYPES)[number]; export type QuestionType = (typeof QUESTION_TYPES)[number];
export const DIFFICULTIES = ['easy', 'medium', 'hard'] as const; export const DIFFICULTIES = ['easy', 'medium', 'hard'] as const;
@ -31,12 +31,17 @@ export type ClassColor = (typeof CLASS_COLORS)[number];
export const QUESTION_TYPE_LABEL: Record<QuestionType, string> = { export const QUESTION_TYPE_LABEL: Record<QuestionType, string> = {
single: 'Multiple choice', single: 'Multiple choice',
multi: 'Select all that apply', multi: 'Select all that apply',
numeric: 'Enter the answer',
}; };
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
/* Stored shapes */ /* Stored shapes */
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
/**
* An answer choice. For numeric questions each option is an accepted answer ("12.5 mL",
* optionally "12.5 ± 0.1 mL"); the student types a value instead of picking one.
*/
export interface Option { export interface Option {
id: string; id: string;
text: string; text: string;
@ -100,13 +105,18 @@ export const questionInputSchema = z
id: z.string().min(1).max(40).optional(), id: z.string().min(1).max(40).optional(),
type: z.enum(QUESTION_TYPES), type: z.enum(QUESTION_TYPES),
stem: z.string().trim().min(1, 'Question text is required').max(LIMITS.markdown), stem: z.string().trim().min(1, 'Question text is required').max(LIMITS.markdown),
options: z.array(optionInputSchema).min(2, 'Add at least two answer choices').max(LIMITS.options), options: z.array(optionInputSchema).min(1, 'Add the correct answer').max(LIMITS.options),
rationale: z.string().max(LIMITS.markdown).optional().default(''), rationale: z.string().max(LIMITS.markdown).optional().default(''),
topic: z.string().trim().max(LIMITS.topic).optional().default(''), topic: z.string().trim().max(LIMITS.topic).optional().default(''),
difficulty: z.enum(DIFFICULTIES).optional().default('medium'), difficulty: z.enum(DIFFICULTIES).optional().default('medium'),
tags: z.array(tagSchema).max(LIMITS.tags).optional().default([]), tags: z.array(tagSchema).max(LIMITS.tags).optional().default([]),
}) })
.superRefine((q, ctx) => { .superRefine((q, ctx) => {
if (q.type === 'numeric') {
if (q.options.some((o) => parseNumericAnswer(o.text) === null)) ctx.addIssue({ code: 'custom', path: ['options'], message: 'Each accepted answer must contain a number' });
return;
}
if (q.options.length < 2) ctx.addIssue({ code: 'custom', path: ['options'], message: 'Add at least two answer choices' });
const correct = q.options.filter((o) => o.correct).length; const correct = q.options.filter((o) => o.correct).length;
if (q.type === 'single' && correct !== 1) { if (q.type === 'single' && correct !== 1) {
ctx.addIssue({ code: 'custom', path: ['options'], message: 'Multiple choice needs exactly one correct answer' }); ctx.addIssue({ code: 'custom', path: ['options'], message: 'Multiple choice needs exactly one correct answer' });
@ -204,6 +214,12 @@ export function validateDraftQuestion(q: DraftQuestion, index: number): Issue[]
const warn = (field: string, message: string) => issues.push({ level: 'warning', index, field, message }); const warn = (field: string, message: string) => issues.push({ level: 'warning', index, field, message });
if (!q.stem?.trim()) err('stem', 'Question text is missing'); if (!q.stem?.trim()) err('stem', 'Question text is missing');
const options = q.options ?? []; const options = q.options ?? [];
if (q.type === 'numeric') {
if (options.length === 0 || options.every((o) => !o.text?.trim())) err('options', 'Enter the correct answer');
else if (options.some((o) => o.text?.trim() && parseNumericAnswer(o.text) === null)) err('options', 'The correct answer must contain a number');
if (!q.rationale?.trim() && !options.some((o) => o.why?.trim())) warn('rationale', 'No rationale');
return issues;
}
if (options.length < 2) err('options', 'Needs at least two answer choices'); if (options.length < 2) err('options', 'Needs at least two answer choices');
if (options.length > LIMITS.options) err('options', `No more than ${LIMITS.options} answer choices`); if (options.length > LIMITS.options) err('options', `No more than ${LIMITS.options} answer choices`);
if (options.some((o) => !o.text?.trim())) err('options', 'An answer choice is empty'); if (options.some((o) => !o.text?.trim())) err('options', 'An answer choice is empty');
@ -248,6 +264,7 @@ export function validateDraft(draft: ContentDraft): Issue[] {
} }
export function blankQuestion(type: QuestionType = 'single'): DraftQuestion { export function blankQuestion(type: QuestionType = 'single'): DraftQuestion {
if (type === 'numeric') return { type, stem: '', options: [{ text: '', correct: true, why: '' }], rationale: '', topic: '', difficulty: 'medium', tags: [] };
return { return {
type, type,
stem: '', stem: '',
@ -289,7 +306,61 @@ export type SataScoring = 'partial' | 'strict';
export interface ScorableQuestion { export interface ScorableQuestion {
type: QuestionType; type: QuestionType;
options: { id: string; correct: boolean }[]; options: { id: string; correct: boolean; text?: string }[];
}
/* ------------------------------------------------------------------ */
/* Numeric answers */
/* ------------------------------------------------------------------ */
export interface NumericAnswer {
value: number;
/** Absolute tolerance; 0 means "equal after rounding noise". */
tolerance: number;
}
const NUMBER = String.raw`[-−]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?|[-−]?\.\d+`;
const NUMBER_RE = new RegExp(String.raw`(${NUMBER})(?:\s*/\s*(${NUMBER}))?`);
const TOLERANCE_RE = new RegExp(String.raw`(?:±|\+/-|\+-|plus or minus)\s*(${NUMBER})`, 'i');
function toNumber(raw: string): number {
return Number(raw.replace(/−/g, '-').replace(/,/g, ''));
}
/**
* Reads the number in an answer and ignores any unit around it: "12.5 mL", "12.5mL/hr",
* "1,250 units", "0.5", ".5", "1/2" and "-3" all work. "12.5 ± 0.1 mL" also sets a tolerance.
* Returns null when there is no number.
*/
export function parseNumericAnswer(text: string | null | undefined): NumericAnswer | null {
if (!text) return null;
const t = text.trim();
const m = NUMBER_RE.exec(t);
if (!m) return null;
let value = toNumber(m[1]);
if (m[2] !== undefined) {
const denominator = toNumber(m[2]);
if (!denominator) return null;
value /= denominator;
}
if (!Number.isFinite(value)) return null;
const tol = TOLERANCE_RE.exec(t.slice(m.index + m[0].length));
const tolerance = tol ? Math.abs(toNumber(tol[1])) : 0;
return { value, tolerance: Number.isFinite(tolerance) ? tolerance : 0 };
}
/** True when the typed answer matches any accepted answer, comparing numbers only. */
export function numericMatches(input: string | null | undefined, accepted: { text?: string; correct: boolean }[]): boolean {
const given = parseNumericAnswer(input);
if (!given) return false;
return accepted.some((o) => {
if (o.correct === false) return false;
const want = parseNumericAnswer(o.text);
if (!want) return false;
// Rounding noise only ("0.30" vs "0.3"), unless the answer states a tolerance.
const slack = Math.max(want.tolerance, 1e-9 * Math.max(1, Math.abs(want.value)));
return Math.abs(given.value - want.value) <= slack;
});
} }
/** /**
@ -300,6 +371,7 @@ export interface ScorableQuestion {
* - multi (strict): all-or-nothing. * - multi (strict): all-or-nothing.
*/ */
export function scoreQuestion(question: ScorableQuestion, selected: string[], sata: SataScoring = 'partial'): number { export function scoreQuestion(question: ScorableQuestion, selected: string[], sata: SataScoring = 'partial'): number {
if (question.type === 'numeric') return numericMatches(selected[0], question.options) ? 1 : 0;
const picked = new Set(selected); const picked = new Set(selected);
const correctIds = question.options.filter((o) => o.correct).map((o) => o.id); const correctIds = question.options.filter((o) => o.correct).map((o) => o.id);
if (correctIds.length === 0 || picked.size === 0) return 0; if (correctIds.length === 0 || picked.size === 0) return 0;
@ -320,6 +392,30 @@ export function isFullyCorrect(score: number): boolean {
return score >= 0.999; return score >= 0.999;
} }
/**
* The 7-point grading scale used by most nursing programs:
* A 93-100, B 85-92, C 77-84, D 70-76, F below 70. Percentages are rounded first, so 92.6% is
* an A. C is the usual minimum passing grade.
*/
export const GRADE_SCALE = [
{ letter: 'A', min: 93 },
{ letter: 'B', min: 85 },
{ letter: 'C', min: 77 },
{ letter: 'D', min: 70 },
{ letter: 'F', min: 0 },
] as const;
export type LetterGrade = (typeof GRADE_SCALE)[number]['letter'];
export function letterGrade(percentScore: number): LetterGrade {
const p = Math.round(percentScore);
return (GRADE_SCALE.find((g) => p >= g.min) ?? GRADE_SCALE[GRADE_SCALE.length - 1]).letter;
}
/** Passing on the 7-point scale means a C (77%) or better. */
export function isPassing(percentScore: number): boolean {
return Math.round(percentScore) >= 77;
}
export function percent(score: number, max: number): number { export function percent(score: number, max: number): number {
if (!max) return 0; if (!max) return 0;
return Math.round((score / max) * 100); return Math.round((score / max) * 100);

View file

@ -18,6 +18,7 @@ import {
type Issue, type Issue,
type NoteDraft, type NoteDraft,
type QuizDraft, type QuizDraft,
parseNumericAnswer,
validateDraft, validateDraft,
} from './content.ts'; } from './content.ts';
@ -122,8 +123,27 @@ function normalizeQuestion(raw: unknown, notices: Issue[], index: number): Draft
notices.push({ level: 'warning', index, message: `Question ${index + 1} is not an object and was skipped` }); notices.push({ level: 'warning', index, message: `Question ${index + 1} is not an object and was skipped` });
return null; return null;
} }
const options = normalizeOptions(pick(raw, 'options', 'choices', 'answers', 'answerOptions', 'answer_options')); let options = normalizeOptions(pick(raw, 'options', 'choices', 'answers', 'answerOptions', 'answer_options'));
const answerKey = pick(raw, 'correctAnswers', 'correct_answers', 'correctAnswer', 'correct_answer', 'answer', 'correct', 'key'); const answerKey = pick(raw, 'correctAnswers', 'correct_answers', 'correctAnswer', 'correct_answer', 'answer', 'correct', 'key');
const rawTypeEarly = str(pick(raw, 'type', 'questionType', 'question_type', 'kind')).toLowerCase().replace(/[\s-]/g, '_');
const numericType = NUMERIC_TYPES.includes(rawTypeEarly);
// Calculation questions: the "options" are the accepted answers, or there is only an answer key.
if (numericType || (options.length === 0 && (typeof answerKey === 'number' || (typeof answerKey === 'string' && parseNumericAnswer(answerKey) !== null)))) {
if (options.length === 0 && answerKey !== undefined) {
const keys = Array.isArray(answerKey) ? answerKey : [answerKey];
options = keys.map((k) => ({ text: str(k).trim(), correct: true, why: '' })).filter((o) => o.text);
}
return {
type: 'numeric',
stem: str(pick(raw, 'stem', 'prompt', 'question', 'text', 'q')).trim(),
options: options.map((o) => ({ ...o, correct: true })),
rationale: str(pick(raw, 'rationale', 'explanation', 'reasoning', 'feedback')).trim(),
topic: str(pick(raw, 'topic', 'category', 'subject', 'concept')).trim().slice(0, 80),
difficulty: toDifficulty(pick(raw, 'difficulty', 'level')),
tags: toTags(pick(raw, 'tags', 'keywords')),
source: str(pick(raw, 'source', 'citation', 'reference')).trim() || undefined,
};
}
if (answerKey !== undefined && !options.some((o) => o.correct)) { if (answerKey !== undefined && !options.some((o) => o.correct)) {
for (const idx of resolveAnswerRefs(answerKey, options)) options[idx].correct = true; for (const idx of resolveAnswerRefs(answerKey, options)) options[idx].correct = true;
} }
@ -195,8 +215,13 @@ function noteFrom(raw: Raw): NoteDraft {
return { kind: 'note', title: str(pick(raw, 'title', 'name')).trim(), content: str(pick(raw, 'content', 'markdown', 'body', 'text')) }; return { kind: 'note', title: str(pick(raw, 'title', 'name')).trim(), content: str(pick(raw, 'content', 'markdown', 'body', 'text')) };
} }
const NUMERIC_TYPES = ['numeric', 'number', 'numerical', 'calculation', 'calc', 'math', 'fill_in', 'fill_in_the_blank', 'short_answer', 'dosage'];
function looksLikeQuestion(v: unknown): boolean { function looksLikeQuestion(v: unknown): boolean {
return isObj(v) && pick(v, 'options', 'choices', 'answers', 'answerOptions') !== undefined; if (!isObj(v)) return false;
if (pick(v, 'options', 'choices', 'answers', 'answerOptions') !== undefined) return true;
const type = str(pick(v, 'type', 'questionType', 'question_type')).toLowerCase().replace(/[\s-]/g, '_');
return NUMERIC_TYPES.includes(type) && pick(v, 'stem', 'question', 'prompt') !== undefined;
} }
function looksLikeCard(v: unknown): boolean { function looksLikeCard(v: unknown): boolean {
return isObj(v) && pick(v, 'front', 'term') !== undefined && pick(v, 'back', 'definition') !== undefined; return isObj(v) && pick(v, 'front', 'term') !== undefined && pick(v, 'back', 'definition') !== undefined;
@ -305,7 +330,7 @@ export function parseTextQuestions(text: string): DraftQuestion[] {
const questions: DraftQuestion[] = []; const questions: DraftQuestion[] = [];
for (const block of blocks) { for (const block of blocks) {
const lines = block.split('\n').filter((l) => l.trim()); const lines = block.split('\n').filter((l) => l.trim());
if (lines.length < 3) continue; if (lines.length < 2) continue;
const stem: string[] = []; const stem: string[] = [];
const options: DraftOption[] = []; const options: DraftOption[] = [];
let rationale = ''; let rationale = '';
@ -343,6 +368,11 @@ export function parseTextQuestions(text: string): DraftQuestion[] {
else if (section === 'rationale') rationale += `\n${line.trim()}`; else if (section === 'rationale') rationale += `\n${line.trim()}`;
else if (options.length) options[options.length - 1].text += ` ${line.trim()}`; else if (options.length) options[options.length - 1].text += ` ${line.trim()}`;
} }
if (stem.length > 0 && options.length === 0 && answer && parseNumericAnswer(answer) !== null) {
// "Answer: 12.5 mL" with no choices: a calculation the student types in.
questions.push({ type: 'numeric', stem: stem.join('\n'), options: [{ text: answer.trim(), correct: true, why: '' }], rationale: rationale.trim(), topic, difficulty: 'medium', tags: [] });
continue;
}
if (options.length < 2 || stem.length === 0) continue; if (options.length < 2 || stem.length === 0) continue;
if (answer && !options.some((o) => o.correct)) for (const idx of resolveAnswerRefs(answer, options)) options[idx].correct = true; if (answer && !options.some((o) => o.correct)) for (const idx of resolveAnswerRefs(answer, options)) options[idx].correct = true;
const correctCount = options.filter((o) => o.correct).length; const correctCount = options.filter((o) => o.correct).length;
@ -513,6 +543,15 @@ export const QUIZ_JSON_TEMPLATE = JSON.stringify(
difficulty: 'medium', difficulty: 'medium',
tags: [], tags: [],
}, },
{
type: 'numeric',
stem: 'Heparin 5,000 units subcut is ordered. The vial contains 10,000 units/mL. How many mL should the nurse give? Round to the nearest tenth.',
options: [{ text: '0.5 mL', correct: true, why: '5,000 units ÷ 10,000 units/mL = 0.5 mL.' }],
rationale: 'Desired over have: 5,000 ÷ 10,000 × 1 mL = 0.5 mL. Only the number is checked, so "0.5" and "0.5 mL" are both accepted.',
topic: 'Dosage calculation',
difficulty: 'easy',
tags: [],
},
], ],
}), }),
null, null,
@ -546,7 +585,12 @@ Topic: Electrolytes
C. Hypertension C. Hypertension
*D. Bradycardia *D. Bradycardia
Rationale: Early toxicity is gastrointestinal and visual; bradycardia and dysrhythmias follow. Rationale: Early toxicity is gastrointestinal and visual; bradycardia and dysrhythmias follow.
Topic: Pharmacology`; Topic: Pharmacology
3. The provider orders 500 mL of normal saline over 4 hours. At what rate in mL/hr should the nurse set the pump?
Answer: 125 mL/hr
Rationale: 500 mL ÷ 4 hr = 125 mL/hr.
Topic: Dosage calculation`;
export const TEXT_CARDS_TEMPLATE = `Furosemide\tLoop diuretic; monitor potassium export const TEXT_CARDS_TEMPLATE = `Furosemide\tLoop diuretic; monitor potassium
Metoprolol\tBeta-1 selective blocker; hold for HR below 60 Metoprolol\tBeta-1 selective blocker; hold for HR below 60
@ -588,9 +632,10 @@ Use exactly this shape:
} }
Rules: Rules:
- "type" is "single" (multiple choice) or "multi" (select all that apply). - "type" is "single" (multiple choice), "multi" (select all that apply) or "numeric" (the student types a number).
- "single" questions have exactly 4 options and exactly one with "correct": true. - "single" questions have exactly 4 options and exactly one with "correct": true.
- "multi" questions have 5 or 6 options, 2 to 5 of them correct, and the stem ends with "Select all that apply." - "multi" questions have 5 or 6 options, 2 to 5 of them correct, and the stem ends with "Select all that apply."
- Use "numeric" for calculations (dosages, IV rates, drip rates, conversions, intake and output). Its "options" holds only the correct answer, e.g. [{ "text": "12.5 mL", "correct": true, "why": "Show the calculation" }]. The stem states the unit and how to round, e.g. "Round to the nearest tenth." Only the number is checked, so units in the answer are optional.
- Write NCLEX-style questions that test clinical judgment: a short client scenario, one clear question, priority wording where it fits (first, best, most important), and distractors that are plausible but wrong for a specific reason. Never use "all of the above" or "none of the above". - Write NCLEX-style questions that test clinical judgment: a short client scenario, one clear question, priority wording where it fits (first, best, most important), and distractors that are plausible but wrong for a specific reason. Never use "all of the above" or "none of the above".
- Every option needs a one-sentence "why". The "rationale" explains the principle behind the correct answer. - Every option needs a one-sentence "why". The "rationale" explains the principle behind the correct answer.
- "topic" is a short label. Reuse the same label for related questions and keep the number of different topics small. - "topic" is a short label. Reuse the same label for related questions and keep the number of different topics small.

View file

@ -3,6 +3,7 @@ import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { createTestApp, PASSWORD, sampleQuestions, type TestApp } from './helpers.ts'; import { createTestApp, PASSWORD, sampleQuestions, type TestApp } from './helpers.ts';
import { queueIdle } from '../server/services/documents.ts';
let t: TestApp; let t: TestApp;
beforeEach(async () => { beforeEach(async () => {
@ -275,14 +276,16 @@ describe('sharing', () => {
expect((await t.api('GET', `/api/public/${rotated.token}`, undefined, anon)).status).toBe(404); expect((await t.api('GET', `/api/public/${rotated.token}`, undefined, anon)).status).toBe(404);
}); });
it('shares a class as a collection without exposing documents', async () => { it("shares a class as a collection without exposing other classes' content", async () => {
const cls = await makeClass(); const cls = await makeClass();
const quizId = (await t.api('POST', '/api/quizzes', { classId: cls.id, title: 'Q', questions: sampleQuestions })).body.quiz.id; const quizId = (await t.api('POST', '/api/quizzes', { classId: cls.id, title: 'Q', questions: sampleQuestions })).body.quiz.id;
const deckId = (await t.api('POST', '/api/decks', { classId: cls.id, title: 'D', cards: [{ front: 'a', back: 'b' }] })).body.deck.id; const deckId = (await t.api('POST', '/api/decks', { classId: cls.id, title: 'D', cards: [{ front: 'a', back: 'b' }] })).body.deck.id;
await t.api('POST', '/api/quizzes', { classId: cls.id, title: 'Empty quiz' }); await t.api('POST', '/api/quizzes', { classId: cls.id, title: 'Empty quiz' });
await t.api('POST', '/api/documents/text', { classId: cls.id, title: 'Secret notes', text: 'private lecture content' });
const other = await makeClass('Other'); const other = await makeClass('Other');
const otherQuiz = (await t.api('POST', '/api/quizzes', { classId: other.id, title: 'Other', questions: sampleQuestions })).body.quiz.id; const otherQuiz = (await t.api('POST', '/api/quizzes', { classId: other.id, title: 'Other', questions: sampleQuestions })).body.quiz.id;
// Documents in the shared class are included once processed (see revision1.test.ts); other classes' never are.
await t.api('POST', '/api/documents/text', { classId: other.id, title: 'Secret notes', text: 'private lecture content' });
await queueIdle(t.ctx);
const share = (await t.api('POST', '/api/shares', { kind: 'class', targetId: cls.id })).body.share; const share = (await t.api('POST', '/api/shares', { kind: 'class', targetId: cls.id })).body.share;
const anon = { cookie: null }; const anon = { cookie: null };

View file

@ -16,6 +16,8 @@ export interface MockAi {
requests: { path: string; headers: http.IncomingHttpHeaders; body: any }[]; requests: { path: string; headers: http.IncomingHttpHeaders; body: any }[];
/** Force the next N chat calls to fail with this status. */ /** Force the next N chat calls to fail with this status. */
failNext: (status: number, times?: number) => void; failNext: (status: number, times?: number) => void;
/** Delay every chat call by this many milliseconds (0 turns it off). */
delayChat: (ms: number) => void;
close: () => Promise<void>; close: () => Promise<void>;
} }
@ -108,11 +110,12 @@ function chooseTool(userText: string, names: string[]): string | null {
export function startMockAi(port = 0): Promise<MockAi> { export function startMockAi(port = 0): Promise<MockAi> {
const requests: MockAi['requests'] = []; const requests: MockAi['requests'] = [];
let fail = { status: 0, times: 0 }; let fail = { status: 0, times: 0 };
let delayMs = 0;
const server = http.createServer((req, res) => { const server = http.createServer((req, res) => {
const chunks: Buffer[] = []; const chunks: Buffer[] = [];
req.on('data', (c) => chunks.push(c)); req.on('data', (c) => chunks.push(c));
req.on('end', () => { req.on('end', async () => {
const raw = Buffer.concat(chunks).toString('utf8'); const raw = Buffer.concat(chunks).toString('utf8');
let body: any = null; let body: any = null;
try { try {
@ -135,6 +138,7 @@ export function startMockAi(port = 0): Promise<MockAi> {
return json(200, { object: 'list', model: body?.model, data: inputs.map((t, index) => ({ object: 'embedding', index, embedding: mockEmbedding(t, dims) })), usage: { prompt_tokens: Math.ceil(inputs.join(' ').length / 4), total_tokens: Math.ceil(inputs.join(' ').length / 4) } }); return json(200, { object: 'list', model: body?.model, data: inputs.map((t, index) => ({ object: 'embedding', index, embedding: mockEmbedding(t, dims) })), usage: { prompt_tokens: Math.ceil(inputs.join(' ').length / 4), total_tokens: Math.ceil(inputs.join(' ').length / 4) } });
} }
if (!path.endsWith('/chat/completions')) return json(404, { error: { message: 'not found' } }); if (!path.endsWith('/chat/completions')) return json(404, { error: { message: 'not found' } });
if (delayMs > 0) await new Promise((r) => setTimeout(r, delayMs));
if (fail.times > 0) { if (fail.times > 0) {
fail.times -= 1; fail.times -= 1;
const kind = fail.status === 401 ? ['Incorrect API key provided', 'invalid_request_error'] : fail.status === 429 ? ['Rate limit reached', 'rate_limit_error'] : ['The server had an error', 'server_error']; const kind = fail.status === 401 ? ['Incorrect API key provided', 'invalid_request_error'] : fail.status === 429 ? ['Rate limit reached', 'rate_limit_error'] : ['The server had an error', 'server_error'];
@ -212,6 +216,9 @@ export function startMockAi(port = 0): Promise<MockAi> {
failNext: (status, times = 1) => { failNext: (status, times = 1) => {
fail = { status, times }; fail = { status, times };
}, },
delayChat: (ms) => {
delayMs = ms;
},
close: () => new Promise((done) => server.close(() => done())), close: () => new Promise((done) => server.close(() => done())),
}); });
}); });

316
tests/revision1.test.ts Normal file
View file

@ -0,0 +1,316 @@
/**
* Regression tests for the first round of V2 revisions: numeric questions, the 7-point grading
* scale, editable instructions and presets, documents in collection shares, background
* assistant turns with stop/re-attach, @-tagged materials, assistant model switching, cached
* pricing and the built-in embedding default.
*/
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest';
import { isPassing, letterGrade, numericMatches, parseNumericAnswer, scoreQuestion } from '../shared/content.ts';
import { parseImport } from '../shared/importer.ts';
import { estimateCost } from '../server/ai/service.ts';
import { queueIdle } from '../server/services/documents.ts';
import { getEmbeddingSettings, setLocalEmbeddingDefault } from '../server/services/semantic.ts';
import { seedTemplates } from '../server/services/templates.ts';
import { createTestApp, type TestApp } from './helpers.ts';
import { startMockAi, type MockAi } from './mockAi.ts';
let mock: MockAi;
let t: TestApp;
beforeAll(async () => {
mock = await startMockAi();
});
afterAll(() => mock.close());
beforeEach(async () => {
t = await createTestApp();
mock.requests.length = 0;
mock.delayChat(0);
});
afterEach(() => t.close());
async function connectAi() {
const provider = (await t.api('POST', '/api/ai/providers', { name: 'Mock', kind: 'openai_compatible', baseUrl: mock.url, apiKey: 'mock-key' })).body.provider;
const models = (await t.api('POST', `/api/ai/providers/${provider.id}/discover`)).body.models as any[];
for (const m of models) await t.api('PATCH', `/api/ai/models/${m.id}`, { enabled: true, capabilities: { tools: true } });
return models;
}
function parseEvents(raw: string): any[] {
return raw
.split(/\n\n/)
.map((block) => block.split('\n').filter((l) => l.startsWith('data:')).map((l) => l.slice(5).trim()).join(''))
.filter(Boolean)
.map((d) => JSON.parse(d));
}
async function sse(url: string, body?: unknown): Promise<any[]> {
const res = await t.raw(body === undefined ? 'GET' : 'POST', url, body === undefined ? {} : { headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
expect(res.status).toBe(200);
return parseEvents(await res.text());
}
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
async function waitIdle(conversationId: string) {
for (let i = 0; i < 400; i += 1) {
const c = (await t.api('GET', `/api/ai/conversations/${conversationId}`)).body;
if (!c.conversation.running) return c;
await sleep(25);
}
throw new Error('turn never finished');
}
/* ------------------------------ numeric answers + grading ------------------------------ */
describe('numeric answers', () => {
it('reads the number and ignores units', () => {
expect(parseNumericAnswer('12.5 mL/hr')).toEqual({ value: 12.5, tolerance: 0 });
expect(parseNumericAnswer('1,250 units')?.value).toBe(1250);
expect(parseNumericAnswer('.5')?.value).toBe(0.5);
expect(parseNumericAnswer('1/4 tab')?.value).toBe(0.25);
expect(parseNumericAnswer('12.5 ± 0.1 mL')).toEqual({ value: 12.5, tolerance: 0.1 });
expect(parseNumericAnswer('no number')).toBeNull();
expect(numericMatches('12.50ml', [{ text: '12.5 mL', correct: true }])).toBe(true);
expect(numericMatches('12.4', [{ text: '12.5 mL', correct: true }])).toBe(false);
expect(numericMatches('12.45', [{ text: '12.5 ± 0.1', correct: true }])).toBe(true);
expect(scoreQuestion({ type: 'numeric', options: [{ id: 'a', text: '0.5 mL', correct: true }] }, ['0.5'])).toBe(1);
expect(scoreQuestion({ type: 'numeric', options: [{ id: 'a', text: '0.5 mL', correct: true }] }, [])).toBe(0);
});
it('imports calculation questions from JSON and from text blocks', () => {
const json = parseImport(JSON.stringify({ kind: 'quiz', title: 'Math', questions: [{ type: 'numeric', stem: 'Rate?', answer: '125 mL/hr', rationale: 'r' }, { question: 'Dose?', correctAnswer: 2 }] }));
const qs = json.items[0].kind === 'quiz' ? json.items[0].questions : [];
expect(qs.map((q) => q.type)).toEqual(['numeric', 'numeric']);
expect(qs[0].options).toEqual([{ text: '125 mL/hr', correct: true, why: '' }]);
const text = parseImport('1. Infuse 500 mL over 4 hours. Rate in mL/hr?\nAnswer: 125 mL/hr\nRationale: 500/4');
expect(text.items[0]).toMatchObject({ kind: 'quiz', questions: [{ type: 'numeric', options: [{ text: '125 mL/hr', correct: true }] }] });
});
it('stores, validates, takes and scores numeric questions through the API', async () => {
const cls = (await t.api('POST', '/api/classes', { name: 'Dosage' })).body.class;
const bad = await t.api('POST', '/api/quizzes', { classId: cls.id, title: 'Bad', questions: [{ type: 'numeric', stem: 'How much?', options: [{ text: 'half a tablet', correct: true }] }] });
expect(bad.status).toBe(422);
const quiz = (
await t.api('POST', '/api/quizzes', {
classId: cls.id,
title: 'Calc',
questions: [
{ type: 'numeric', stem: 'Give how many mL?', options: [{ text: '0.5 mL', correct: true, why: '5000/10000' }], rationale: 'Desired over have' },
{ type: 'numeric', stem: 'Rate?', options: [{ text: '125 mL/hr', correct: true }] },
],
})
).body.quiz;
const attempt = (await t.api('POST', '/api/attempts', { mode: 'practice', source: { type: 'quiz', quizId: quiz.id }, shuffleQuestions: false })).body.attempt;
const [q1, q2] = attempt.questions;
const patched = (await t.api('PATCH', `/api/attempts/${attempt.id}`, { answers: { [q1.id]: { selected: ['0.50 ml'], checked: true }, [q2.id]: { selected: ['120'], checked: true } } })).body.attempt;
expect(patched.answers[q1.id].selected).toEqual(['0.50 ml']);
const done = (await t.api('POST', `/api/attempts/${attempt.id}/complete`, {})).body.attempt;
expect(done.score).toBe(1);
expect(done.maxScore).toBe(2);
expect(done.results[q1.id].correct).toBe(true);
expect(done.results[q2.id].correct).toBe(false);
});
});
describe('7-point grading scale', () => {
it('maps percentages to letters with C as the passing grade', () => {
expect([100, 93, 92.6, 92, 85, 84, 77, 76, 70, 69, 0].map(letterGrade)).toEqual(['A', 'A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'F', 'F']);
expect(isPassing(77)).toBe(true);
expect(isPassing(76)).toBe(false);
});
});
/* ------------------------------ pricing ------------------------------ */
describe('cost estimates', () => {
it('bills cached input at the cached price and applies DeepSeek off-peak pricing', () => {
const offPeak = Date.UTC(2026, 10, 16, 12, 0);
const flash = { model: 'deepseek-flash', providerKind: 'deepseek' as const, priceIn: 0.3, priceOut: 1.2, priceCachedIn: 0.006 };
const cost = estimateCost(flash, { inputTokens: 1_000_000, cacheReadTokens: 800_000, outputTokens: 100_000 }, offPeak)!;
// (200k * 0.3 + 800k * 0.006 + 100k * 1.2) / 1M, halved off-peak
expect(cost).toBeCloseTo(((200_000 * 0.3 + 800_000 * 0.006 + 100_000 * 1.2) / 1_000_000) * 0.5, 8);
const claude = { model: 'claude-sonnet-5-5', providerKind: 'anthropic' as const, priceIn: 2, priceOut: 10, priceCachedIn: null };
expect(estimateCost(claude, { inputTokens: 1_000_000, cacheReadTokens: 500_000, cacheWriteTokens: 100_000, outputTokens: 0 })!).toBeCloseTo((400_000 * 2 + 500_000 * 0.2 + 100_000 * 2.5) / 1_000_000, 8);
expect(estimateCost({ model: 'x', providerKind: 'openai_compatible', priceIn: null, priceOut: null }, { inputTokens: 5, outputTokens: 5 })).toBeNull();
});
it('stores an editable cached price per model', async () => {
const models = await connectAi();
const updated = (await t.api('PATCH', `/api/ai/models/${models[0].id}`, { priceIn: 1, priceOut: 2, priceCachedIn: 0.05 })).body.model;
expect(updated.priceCachedIn).toBe(0.05);
const cleared = (await t.api('PATCH', `/api/ai/models/${models[0].id}`, { priceCachedIn: null })).body.model;
expect(cleared.priceCachedIn).toBeNull();
});
it('accepts the full range of reasoning efforts in task settings', async () => {
for (const effort of ['minimal', 'xhigh', 'max']) {
const res = await t.api('PUT', '/api/ai/tasks', { chat: { modelId: null, temperature: null, reasoningEffort: effort, maxOutputTokens: null } });
expect(res.status).toBe(200);
expect(res.body.tasks.chat.reasoningEffort).toBe(effort);
}
});
});
/* ------------------------------ instructions + presets ------------------------------ */
describe('editable generation instructions and presets', () => {
it('saves and resets generator instructions, which generation then uses', async () => {
const list = (await t.api('GET', '/api/ai/instructions')).body.instructions as any[];
expect(list.find((i) => i.key === 'quiz.nclex').text).toMatch(/numeric/);
const custom = 'Write every question about pediatric dosing. Calculation items use type numeric.';
const saved = (await t.api('PUT', '/api/ai/instructions', { key: 'quiz.nclex', text: custom })).body.instructions as any[];
expect(saved.find((i) => i.key === 'quiz.nclex')).toMatchObject({ text: custom, customized: true });
await connectAi();
const cls = (await t.api('POST', '/api/classes', { name: 'Peds' })).body.class;
const { draftId } = (await t.api('POST', '/api/ai/generate', { kind: 'quiz', classId: cls.id, focus: 'fever', count: 2 })).body;
for (let i = 0; i < 200 && (await t.api('GET', `/api/drafts/${draftId}`)).body.draft.status === 'generating'; i += 1) await sleep(25);
const call = mock.requests.find((r) => r.path.endsWith('/chat/completions'))!;
expect(JSON.stringify(call.body.messages[0])).toContain('pediatric dosing');
const reset = (await t.api('PUT', '/api/ai/instructions', { key: 'quiz.nclex', text: null })).body.instructions as any[];
expect(reset.find((i) => i.key === 'quiz.nclex').customized).toBe(false);
});
it('keeps the chatbot import instructions separate and editable', async () => {
const before = (await t.api('GET', '/api/llm-instructions')).body;
expect(before.builtin.quiz).toContain('"numeric"');
await t.api('PUT', '/api/llm-instructions', { kind: 'quiz', text: 'My own chatbot instructions, long enough.' });
const after = (await t.api('GET', '/api/llm-instructions')).body;
expect(after.quiz).toBe('My own chatbot instructions, long enough.');
expect(after.customized.quiz).toBe(true);
// The built-in generator's instructions are untouched.
expect((await t.api('GET', '/api/ai/instructions')).body.instructions.every((i: any) => !i.customized)).toBe(true);
});
it('lets built-in presets be edited, keeps the edit across restarts and resets it', async () => {
const preset = (await t.api('GET', '/api/templates?kind=generation')).body.templates.find((x: any) => x.id === 'builtin-gen-nclex');
const edited = (await t.api('PATCH', `/api/templates/${preset.id}`, { name: 'My NCLEX set', payload: { ...preset.payload, count: 40 } })).body.template;
expect(edited).toMatchObject({ name: 'My NCLEX set', builtin: true, edited: true });
seedTemplates(t.ctx.db);
const afterSeed = (await t.api('GET', '/api/templates?kind=generation')).body.templates.find((x: any) => x.id === preset.id);
expect(afterSeed).toMatchObject({ name: 'My NCLEX set', edited: true });
expect(afterSeed.payload.count).toBe(40);
const reset = (await t.api('POST', `/api/templates/${preset.id}/reset`)).body.template;
expect(reset).toMatchObject({ name: preset.name, edited: false });
expect(reset.payload.count).toBe(preset.payload.count);
// Built-ins still cannot be deleted.
expect((await t.api('DELETE', `/api/templates/${preset.id}`)).status).toBe(404);
});
});
/* ------------------------------ sharing ------------------------------ */
describe('class shares include documents', () => {
it('lists processed documents and serves them only through the share', async () => {
const cls = (await t.api('POST', '/api/classes', { name: 'Shared' })).body.class;
const doc = (await t.api('POST', '/api/documents/text', { classId: cls.id, title: 'Lecture notes', text: 'Furosemide causes potassium loss.' })).body.document;
await queueIdle(t.ctx);
const other = (await t.api('POST', '/api/classes', { name: 'Private' })).body.class;
const hidden = (await t.api('POST', '/api/documents/text', { classId: other.id, title: 'Private notes', text: 'secret' })).body.document;
await queueIdle(t.ctx);
const share = (await t.api('POST', '/api/shares', { kind: 'class', targetId: cls.id })).body.share;
const anon = { cookie: null };
const pub = (await t.api('GET', `/api/public/${share.token}`, undefined, anon)).body;
expect(pub.items).toEqual([expect.objectContaining({ kind: 'document', id: doc.id, title: 'Lecture notes' })]);
const meta = (await t.api('GET', `/api/public/${share.token}/items/document/${doc.id}`, undefined, anon)).body;
expect(meta).toMatchObject({ kind: 'document', id: doc.id });
const file = await t.raw('GET', `/api/public/${share.token}/items/document/${doc.id}/file`, { cookie: null });
expect(file.status).toBe(200);
expect(await file.text()).toContain('potassium');
expect((await t.raw('GET', `/api/public/${share.token}/items/document/${hidden.id}/file`, { cookie: null })).status).toBe(404);
// Turning the share off closes the file route too.
await t.api('PATCH', `/api/shares/${share.id}`, { enabled: false });
expect((await t.raw('GET', `/api/public/${share.token}/items/document/${doc.id}/file`, { cookie: null })).status).toBe(404);
});
});
/* ------------------------------ assistant ------------------------------ */
describe('assistant turns', () => {
it('keeps answering after the browser disconnects, and can be followed again', async () => {
await connectAi();
mock.delayChat(150);
const res = await t.raw('POST', '/api/ai/chat', { headers: { 'content-type': 'application/json' }, body: JSON.stringify({ message: 'Explain the difference between left-sided and right-sided heart failure' }) });
const reader = res.body!.getReader();
const first = new TextDecoder().decode((await reader.read()).value);
const conversationId = parseEvents(first).find((e) => e.type === 'start').conversationId;
// Leave the page.
await reader.cancel();
expect((await t.api('GET', `/api/ai/conversations/${conversationId}`)).body.conversation.running).toBe(true);
expect((await t.api('GET', '/api/ai/conversations')).body.conversations.find((c: any) => c.id === conversationId).running).toBe(true);
// Come back: the stream replays from the start of the turn and runs to the end.
const replay = await sse(`/api/ai/chat/${conversationId}/stream`);
expect(replay[0].type).toBe('start');
expect(replay.at(-1).type).toBe('done');
const convo = await waitIdle(conversationId);
expect(convo.messages.map((m: any) => m.role)).toEqual(['user', 'assistant']);
expect(convo.messages[1].text.length).toBeGreaterThan(10);
// Following a finished conversation ends at once.
expect((await sse(`/api/ai/chat/${conversationId}/stream`)).map((e) => e.type)).toEqual(['done']);
});
it('stops only when asked, and refuses a second turn while one is running', async () => {
await connectAi();
mock.delayChat(300);
const res = await t.raw('POST', '/api/ai/chat', { headers: { 'content-type': 'application/json' }, body: JSON.stringify({ message: 'Tell me about digoxin' }) });
const reader = res.body!.getReader();
const conversationId = parseEvents(new TextDecoder().decode((await reader.read()).value)).find((e) => e.type === 'start').conversationId;
await reader.cancel();
const busy = await sse('/api/ai/chat', { conversationId, message: 'And another thing' });
expect(busy.find((e) => e.type === 'error').code).toBe('busy');
expect((await t.api('POST', `/api/ai/chat/${conversationId}/stop`)).body.stopped).toBe(true);
const convo = await waitIdle(conversationId);
expect(convo.messages.at(-1).text).toContain('Stopped');
expect((await t.api('POST', `/api/ai/chat/${conversationId}/stop`)).body.stopped).toBe(false);
});
it('passes tagged materials to the model and remembers them on the message', async () => {
await connectAi();
const cls = (await t.api('POST', '/api/classes', { name: 'Pharm' })).body.class;
const quiz = (await t.api('POST', '/api/quizzes', { classId: cls.id, title: 'Cardiac drugs quiz' })).body.quiz;
const deck = (await t.api('POST', '/api/decks', { classId: cls.id, title: 'Antibiotics deck', cards: [{ front: 'a', back: 'b' }] })).body.deck;
const items = (await t.api('GET', `/api/ai/mentionables?classId=${cls.id}`)).body.items as any[];
expect(items.map((i) => i.title).sort()).toEqual(['Antibiotics deck', 'Cardiac drugs quiz']);
expect((await t.api('GET', '/api/ai/mentionables?q=antib')).body.items.map((i: any) => i.id)).toEqual([deck.id]);
const events = await sse('/api/ai/chat', { message: 'Make flashcards from this', context: { classId: cls.id, items: [{ kind: 'quiz', id: quiz.id }, { kind: 'deck', id: 'no-such-deck-xyz' }] } });
const call = mock.requests.find((r) => r.path.endsWith('/chat/completions'))!;
const system = JSON.stringify(call.body.messages[0]);
expect(system).toContain('tagged these materials');
expect(system).toContain(`quiz \\"Cardiac drugs quiz\\" — id ${quiz.id}`);
expect(system).not.toContain('no-such-deck-xyz');
const convo = await waitIdle(events[0].conversationId);
expect(convo.messages[0].tags).toEqual([{ kind: 'quiz', id: quiz.id, title: 'Cardiac drugs quiz' }]);
});
it('uses the model chosen for the chat', async () => {
const models = await connectAi();
const small = models.find((m) => m.model === 'mock-small');
const events = await sse('/api/ai/chat', { message: 'Explain the difference between left-sided and right-sided heart failure', modelId: small.id });
expect(events[0]).toMatchObject({ type: 'start', model: small.label });
expect(mock.requests.filter((r) => r.path.endsWith('/chat/completions')).every((r) => r.body.model === 'mock-small')).toBe(true);
});
});
/* ------------------------------ semantic search default ------------------------------ */
describe('built-in embeddings', () => {
it('is the default until another choice is saved, and can be turned off', async () => {
setLocalEmbeddingDefault(true);
try {
expect(getEmbeddingSettings(t.ctx.db)).toMatchObject({ providerId: 'local', model: 'Xenova/bge-small-en-v1.5' });
const status = (await t.api('GET', '/api/ai/embeddings')).body;
expect(status.local).toMatchObject({ model: 'Xenova/bge-small-en-v1.5', dimensions: 384 });
await t.api('PUT', '/api/ai/embeddings', { providerId: null, model: '', dimensions: null });
expect(getEmbeddingSettings(t.ctx.db).providerId).toBeNull();
await t.api('PUT', '/api/ai/embeddings', { providerId: 'local', model: '', dimensions: null });
expect(getEmbeddingSettings(t.ctx.db)).toMatchObject({ providerId: 'local', model: 'Xenova/bge-small-en-v1.5' });
} finally {
setLocalEmbeddingDefault(false);
}
});
});

View file

@ -8,9 +8,10 @@ import { api, errorMessage } from '@/lib/api';
import { assistant, useAssistantState } from '@/lib/assistantStore'; import { assistant, useAssistantState } from '@/lib/assistantStore';
import { qk, useClasses, useOverview, useRefresh } from '@/lib/queries'; import { qk, useClasses, useOverview, useRefresh } from '@/lib/queries';
import type { ClassInfo, SearchHit } from '@/lib/types'; import type { ClassInfo, SearchHit } from '@/lib/types';
import { cx, modKey, useDebounced, useHotkeys, useIsDesktop, useTheme, type ThemeChoice } from '@/lib/util'; import { cx, useDebounced, useHotkeys, useIsDesktop, useTheme, type ThemeChoice } from '@/lib/util';
import { Brand } from '@/pages/Auth'; import { Brand } from '@/pages/Auth';
import { Button, ClassDot, Dialog, Field, IconButton, Input, Kbd, Menu, MenuItem, MenuLabel, MenuSeparator, Spinner, Textarea } from '@/ui'; import { Button, ClassDot, Dialog, Field, IconButton, Input, Menu, MenuItem, MenuLabel, MenuSeparator, Spinner, Textarea, Tooltip } from '@/ui';
import { SidebarDrafts, useDraftNotifications } from '@/features/DraftsTray';
const AssistantPanel = lazy(() => import('@/features/AssistantPanel')); const AssistantPanel = lazy(() => import('@/features/AssistantPanel'));
@ -260,18 +261,6 @@ function CommandPalette({ open, onOpenChange, onNewClass }: { open: boolean; onO
)) ))
)} )}
</div> </div>
<div className="hidden items-center gap-4 border-t border-line px-5 py-2.5 text-xs text-ink-3 sm:flex">
<span className="flex items-center gap-1.5">
<Kbd>↑</Kbd>
<Kbd>↓</Kbd> to move
</span>
<span className="flex items-center gap-1.5">
<Kbd>Enter</Kbd> to open
</span>
<span className="flex items-center gap-1.5">
<Kbd>Esc</Kbd> to close
</span>
</div>
</div> </div>
</Dialog> </Dialog>
); );
@ -350,7 +339,6 @@ function Sidebar({ onSearch, onNewClass }: { onSearch: () => void; onNewClass: (
<button type="button" onClick={onSearch} className="flex h-9 w-full items-center gap-2 rounded-[10px] border border-line-strong bg-surface px-2.5 text-sm text-ink-3 shadow-1 hover:border-ink-3"> <button type="button" onClick={onSearch} className="flex h-9 w-full items-center gap-2 rounded-[10px] border border-line-strong bg-surface px-2.5 text-sm text-ink-3 shadow-1 hover:border-ink-3">
<Search className="size-4" aria-hidden /> <Search className="size-4" aria-hidden />
<span className="flex-1 text-left">Search</span> <span className="flex-1 text-left">Search</span>
<Kbd>{modKey} K</Kbd>
</button> </button>
</div> </div>
<nav aria-label="Main" className="space-y-0.5 px-3"> <nav aria-label="Main" className="space-y-0.5 px-3">
@ -368,6 +356,8 @@ function Sidebar({ onSearch, onNewClass }: { onSearch: () => void; onNewClass: (
</NavItem> </NavItem>
</nav> </nav>
<SidebarDrafts />
<div className="mt-5 flex items-center justify-between px-5 pb-1.5"> <div className="mt-5 flex items-center justify-between px-5 pb-1.5">
<span className="eyebrow">Classes</span> <span className="eyebrow">Classes</span>
<IconButton label="New class" size="sm" onClick={onNewClass} className="-mr-2 size-7"> <IconButton label="New class" size="sm" onClick={onNewClass} className="-mr-2 size-7">
@ -539,6 +529,7 @@ export function Shell() {
const navigate = useNavigate(); const navigate = useNavigate();
const location = useLocation(); const location = useLocation();
const { open: assistantOpen, seed } = useAssistantState(); const { open: assistantOpen, seed } = useAssistantState();
useDraftNotifications();
const onAssistantPage = location.pathname.startsWith('/assistant'); const onAssistantPage = location.pathname.startsWith('/assistant');
// Study screens lay themselves out edge to edge and bring their own header and footer. // Study screens lay themselves out edge to edge and bring their own header and footer.
const immersive = location.pathname === '/review' || /^\/decks\/[^/]+\/cram$/.test(location.pathname); const immersive = location.pathname === '/review' || /^\/decks\/[^/]+\/cram$/.test(location.pathname);
@ -581,7 +572,8 @@ export function Shell() {
<Sidebar onSearch={() => setPaletteOpen(true)} onNewClass={() => setClassDialog(true)} /> <Sidebar onSearch={() => setPaletteOpen(true)} onNewClass={() => setClassDialog(true)} />
<div className="flex min-w-0 flex-1 flex-col"> <div className="flex min-w-0 flex-1 flex-col">
{!immersive && <MobileNav onSearch={() => setPaletteOpen(true)} onNewClass={() => setClassDialog(true)} />} {!immersive && <MobileNav onSearch={() => setPaletteOpen(true)} onNewClass={() => setClassDialog(true)} />}
<main id="main" tabIndex={-1} className={cx('w-full flex-1 outline-none', !immersive && 'mx-auto max-w-[1080px] px-4 pt-6 pb-28 sm:px-8 lg:pt-10 lg:pb-16')}> {/* The assistant page lays itself out edge to edge; other pages sit in the reading column. */}
<main id="main" tabIndex={-1} className={cx('w-full flex-1 outline-none', !immersive && !onAssistantPage && 'mx-auto max-w-[1080px] px-4 pt-6 pb-28 sm:px-8 lg:pt-10 lg:pb-16')}>
<Outlet /> <Outlet />
</main> </main>
</div> </div>
@ -600,15 +592,16 @@ export function Shell() {
</aside> </aside>
)} )}
{!showDrawer && !onAssistantPage && !immersive && isDesktop && ( {!showDrawer && !onAssistantPage && !immersive && isDesktop && (
<button <Tooltip label="Assistant" side="left">
type="button" <button
onClick={() => assistant.open()} type="button"
className="fixed right-6 bottom-6 z-20 flex h-11 items-center gap-2 rounded-full bg-ink pr-4 pl-3.5 text-sm font-medium text-paper shadow-2 transition-transform hover:-translate-y-0.5" aria-label="Open the assistant"
> onClick={() => assistant.open()}
<Sparkles className="size-4 text-marker" /> className="fixed right-5 bottom-5 z-20 grid size-10 place-items-center rounded-full border border-line-strong bg-surface/90 text-ink-2 shadow-1 backdrop-blur transition-colors hover:border-ink-3 hover:text-ink"
Assistant >
<span className="ml-1 rounded border border-paper/25 px-1 py-px font-mono text-[10px] text-paper/70">{modKey} J</span> <Sparkles className="size-[18px]" />
</button> </button>
</Tooltip>
)} )}
<CommandPalette open={paletteOpen} onOpenChange={setPaletteOpen} onNewClass={() => setClassDialog(true)} /> <CommandPalette open={paletteOpen} onOpenChange={setPaletteOpen} onNewClass={() => setClassDialog(true)} />
<ClassDialog open={classDialog} onOpenChange={setClassDialog} /> <ClassDialog open={classDialog} onOpenChange={setClassDialog} />

View file

@ -5,7 +5,7 @@ import { toast } from 'sonner';
import { api, errorMessage } from '@/lib/api'; import { api, errorMessage } from '@/lib/api';
import { qk } from '@/lib/queries'; import { qk } from '@/lib/queries';
import { SemanticSettings } from './SemanticSettings'; import { SemanticSettings } from './SemanticSettings';
import type { AdapterMeta, AiModel, AiStatus, Provider, ProviderKind, TaskConfig, TaskName, TaskSettings } from '@/lib/types'; import { REASONING_EFFORTS, type AdapterMeta, type AiModel, type AiStatus, type Provider, type ProviderKind, type TaskConfig, type TaskName, type TaskSettings } from '@/lib/types';
import { cx, formatCost, formatTokens, plural, timeAgo } from '@/lib/util'; import { cx, formatCost, formatTokens, plural, timeAgo } from '@/lib/util';
import { Badge, Button, Callout, Dialog, EmptyState, Field, IconButton, Input, Menu, MenuItem, MenuSeparator, Section, Select, Skeleton, Switch, Textarea, Tooltip, useConfirm } from '@/ui'; import { Badge, Button, Callout, Dialog, EmptyState, Field, IconButton, Input, Menu, MenuItem, MenuSeparator, Section, Select, Skeleton, Switch, Textarea, Tooltip, useConfirm } from '@/ui';
@ -19,6 +19,7 @@ const KIND_BLURB: Record<ProviderKind, string> = {
openai: 'GPT models with an OpenAI API key.', openai: 'GPT models with an OpenAI API key.',
anthropic: 'Claude models with an Anthropic API key.', anthropic: 'Claude models with an Anthropic API key.',
gemini: 'Gemini models with a Google AI Studio key.', gemini: 'Gemini models with a Google AI Studio key.',
deepseek: 'DeepSeek Flash and Pro with a DeepSeek platform key.',
openai_compatible: 'OpenRouter, Groq, Together, LM Studio, vLLM and other compatible servers.', openai_compatible: 'OpenRouter, Groq, Together, LM Studio, vLLM and other compatible servers.',
ollama: 'Models running on your own machine or server.', ollama: 'Models running on your own machine or server.',
}; };
@ -182,6 +183,34 @@ function ProviderDialog({ open, onClose, adapters, existing, onSaved }: { open:
/* ------------------------------ model dialog ------------------------------ */ /* ------------------------------ model dialog ------------------------------ */
/** The discount a provider gives on cached input when a model has no cached price of its own (mirrors the server). */
const CACHE_HINT: Record<ProviderKind, string> = {
openai: "OpenAI's discount (90% off for GPT-5 and later)",
anthropic: "Claude's cache-read rate (10% of input)",
gemini: "Gemini's cache rate (10% of input)",
deepseek: "DeepSeek's cache-hit rate",
openai_compatible: 'the normal input price',
ollama: 'the normal input price',
};
function cachedGuess(model: AiModel): string {
const id = model.model.slice(model.model.lastIndexOf('/') + 1);
const ratio =
model.providerKind === 'openai'
? /^gpt-4\.1/.test(id)
? 0.25
: /^(gpt-4o|o\d)/.test(id)
? 0.5
: 0.1
: model.providerKind === 'anthropic' || model.providerKind === 'gemini'
? 0.1
: model.providerKind === 'deepseek'
? 0.02
: 1;
const v = (model.priceIn ?? 0) * ratio;
return `$${v < 0.01 ? v.toFixed(4) : v.toFixed(3)}`;
}
function ModelDialog({ model, onClose, onSaved }: { model: AiModel | null; onClose: () => void; onSaved: () => void }) { function ModelDialog({ model, onClose, onSaved }: { model: AiModel | null; onClose: () => void; onSaved: () => void }) {
const [label, setLabel] = useState(''); const [label, setLabel] = useState('');
const [caps, setCaps] = useState(model?.capabilities ?? { tools: true, vision: false, pdf: false, reasoning: false, temperature: true }); const [caps, setCaps] = useState(model?.capabilities ?? { tools: true, vision: false, pdf: false, reasoning: false, temperature: true });
@ -189,6 +218,7 @@ function ModelDialog({ model, onClose, onSaved }: { model: AiModel | null; onClo
const [maxOut, setMaxOut] = useState(''); const [maxOut, setMaxOut] = useState('');
const [priceIn, setPriceIn] = useState(''); const [priceIn, setPriceIn] = useState('');
const [priceOut, setPriceOut] = useState(''); const [priceOut, setPriceOut] = useState('');
const [priceCached, setPriceCached] = useState('');
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
useEffect(() => { useEffect(() => {
if (!model) return; if (!model) return;
@ -198,13 +228,14 @@ function ModelDialog({ model, onClose, onSaved }: { model: AiModel | null; onClo
setMaxOut(model.maxOutput?.toString() ?? ''); setMaxOut(model.maxOutput?.toString() ?? '');
setPriceIn(model.priceIn?.toString() ?? ''); setPriceIn(model.priceIn?.toString() ?? '');
setPriceOut(model.priceOut?.toString() ?? ''); setPriceOut(model.priceOut?.toString() ?? '');
setPriceCached(model.priceCachedIn?.toString() ?? '');
}, [model]); }, [model]);
const num = (s: string) => (s.trim() === '' ? null : Number(s)); const num = (s: string) => (s.trim() === '' ? null : Number(s));
const save = async () => { const save = async () => {
if (!model) return; if (!model) return;
setBusy(true); setBusy(true);
try { try {
await api.patch(`/api/ai/models/${model.id}`, { label, capabilities: caps, contextWindow: num(ctx), maxOutput: num(maxOut), priceIn: num(priceIn), priceOut: num(priceOut) }); await api.patch(`/api/ai/models/${model.id}`, { label, capabilities: caps, contextWindow: num(ctx), maxOutput: num(maxOut), priceIn: num(priceIn), priceOut: num(priceOut), priceCachedIn: num(priceCached) });
onSaved(); onSaved();
onClose(); onClose();
} catch (e) { } catch (e) {
@ -254,6 +285,9 @@ function ModelDialog({ model, onClose, onSaved }: { model: AiModel | null; onClo
<Field label="Output price" hint="USD per million tokens"> <Field label="Output price" hint="USD per million tokens">
<Input type="number" min={0} step="0.01" value={priceOut} onChange={(e) => setPriceOut(e.target.value)} placeholder="Unknown" /> <Input type="number" min={0} step="0.01" value={priceOut} onChange={(e) => setPriceOut(e.target.value)} placeholder="Unknown" />
</Field> </Field>
<Field label="Cached input price" hint={`USD per million cached (cache-hit) input tokens. Blank uses ${model ? CACHE_HINT[model.providerKind] : 'the provider discount'}.`} className="col-span-2">
<Input type="number" min={0} step="0.001" value={priceCached} onChange={(e) => setPriceCached(e.target.value)} placeholder={model?.priceIn != null ? `About ${cachedGuess(model)}` : 'Unknown'} />
</Field>
</div> </div>
</div> </div>
</Dialog> </Dialog>
@ -495,10 +529,11 @@ function TaskRow({ name, label, description, config, models, resolved, onChange
<Field label="Reasoning effort" hint={model && !model.capabilities.reasoning ? 'Not supported by this model' : undefined}> <Field label="Reasoning effort" hint={model && !model.capabilities.reasoning ? 'Not supported by this model' : undefined}>
<Select value={config.reasoningEffort ?? ''} onChange={(e) => onChange({ ...config, reasoningEffort: (e.target.value || null) as TaskConfig['reasoningEffort'] })}> <Select value={config.reasoningEffort ?? ''} onChange={(e) => onChange({ ...config, reasoningEffort: (e.target.value || null) as TaskConfig['reasoningEffort'] })}>
<option value="">Model default</option> <option value="">Model default</option>
<option value="none">Off / minimal</option> {REASONING_EFFORTS.map((e) => (
<option value="low">Low</option> <option key={e.value} value={e.value}>
<option value="medium">Medium</option> {e.label}
<option value="high">High</option> </option>
))}
</Select> </Select>
</Field> </Field>
<Field label="Temperature" hint={model && !model.capabilities.temperature ? 'Ignored by this model' : '0 to 2'}> <Field label="Temperature" hint={model && !model.capabilities.temperature ? 'Ignored by this model' : '0 to 2'}>
@ -536,13 +571,14 @@ function Usage() {
<div className="card px-4 py-5 text-sm text-ink-2">No AI requests in this period.</div> <div className="card px-4 py-5 text-sm text-ink-2">No AI requests in this period.</div>
) : ( ) : (
<div className="card overflow-hidden"> <div className="card overflow-hidden">
<div className="grid grid-cols-3 divide-x divide-line border-b border-line"> <div className="grid grid-cols-2 gap-px border-b border-line bg-line sm:grid-cols-4">
{[ {[
['Estimated cost', formatCost(u.total.cost)], ['Estimated cost', formatCost(u.total.cost)],
['Requests', u.total.calls.toLocaleString()], ['Requests', u.total.calls.toLocaleString()],
['Tokens in / out', `${formatTokens(u.total.input)} / ${formatTokens(u.total.output)}`], ['Tokens in / out', `${formatTokens(u.total.input)} / ${formatTokens(u.total.output)}`],
['Cached input', u.total.input ? `${formatTokens(u.total.cached)} (${Math.round((u.total.cached / u.total.input) * 100)}%)` : '0'],
].map(([k, v]) => ( ].map(([k, v]) => (
<div key={k} className="px-4 py-3"> <div key={k} className="bg-surface px-4 py-3">
<div className="eyebrow">{k}</div> <div className="eyebrow">{k}</div>
<div className="num mt-1 text-lg font-semibold">{v}</div> <div className="num mt-1 text-lg font-semibold">{v}</div>
</div> </div>
@ -555,6 +591,7 @@ function Usage() {
<th className="px-4 py-2 font-medium">Model</th> <th className="px-4 py-2 font-medium">Model</th>
<th className="px-3 py-2 text-right font-medium">Requests</th> <th className="px-3 py-2 text-right font-medium">Requests</th>
<th className="px-3 py-2 text-right font-medium">In</th> <th className="px-3 py-2 text-right font-medium">In</th>
<th className="px-3 py-2 text-right font-medium">Cached</th>
<th className="px-3 py-2 text-right font-medium">Out</th> <th className="px-3 py-2 text-right font-medium">Out</th>
<th className="px-4 py-2 text-right font-medium">Cost</th> <th className="px-4 py-2 text-right font-medium">Cost</th>
</tr> </tr>
@ -571,6 +608,7 @@ function Usage() {
</td> </td>
<td className="num px-3 py-2 text-right">{m.calls}</td> <td className="num px-3 py-2 text-right">{m.calls}</td>
<td className="num px-3 py-2 text-right">{formatTokens(m.input)}</td> <td className="num px-3 py-2 text-right">{formatTokens(m.input)}</td>
<td className="num px-3 py-2 text-right">{formatTokens(m.cached)}</td>
<td className="num px-3 py-2 text-right">{formatTokens(m.output)}</td> <td className="num px-3 py-2 text-right">{formatTokens(m.output)}</td>
<td className="num px-4 py-2 text-right">{m.unpriced > 0 && !m.cost ? 'no price set' : formatCost(m.cost)}</td> <td className="num px-4 py-2 text-right">{m.unpriced > 0 && !m.cost ? 'no price set' : formatCost(m.cost)}</td>
</tr> </tr>

View file

@ -1,13 +1,13 @@
import { useQuery, useQueryClient } from '@tanstack/react-query'; import { useQuery, useQueryClient } from '@tanstack/react-query';
import { ArrowUp, BookOpen, Check, ChevronRight, CircleAlert, FileText, History, Layers, LoaderCircle, NotebookPen, Play, Plus, Sparkles, Square, Trash2, X } from 'lucide-react'; import { ArrowUp, AtSign, BookOpen, Check, ChevronDown, ChevronRight, CircleAlert, FileText, Folder, History, Layers, LoaderCircle, NotebookPen, Play, Plus, Sparkles, Square, Trash2, X } from 'lucide-react';
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { Link, useNavigate } from 'react-router'; import { Link, useNavigate } from 'react-router';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { api, errorMessage, streamEvents } from '@/lib/api'; import { api, errorMessage, streamEvents } from '@/lib/api';
import { assistant, useAssistantState } from '@/lib/assistantStore'; import { assistant, useAssistantState } from '@/lib/assistantStore';
import { useAiStatus, useClasses, useRefresh } from '@/lib/queries'; import { useAiModels, useAiStatus, useClasses, useRefresh } from '@/lib/queries';
import type { AssistantEvent, ChatMessage, ToolActivity, UiItem } from '@/lib/types'; import type { AssistantEvent, ChatMessage, Mentionable, TaggedItem, TagKind, ToolActivity, UiItem } from '@/lib/types';
import { cx, plural, timeAgo } from '@/lib/util'; import { cx, plural, timeAgo, useDebounced, useLocalStorage } from '@/lib/util';
import { citedSources, Markdown, type Citation } from '@/ui/Markdown'; import { citedSources, Markdown, type Citation } from '@/ui/Markdown';
import { Badge, Button, Callout, IconButton, Menu, MenuItem, MenuLabel, MenuSeparator, Spinner } from '@/ui'; import { Badge, Button, Callout, IconButton, Menu, MenuItem, MenuLabel, MenuSeparator, Spinner } from '@/ui';
@ -16,6 +16,7 @@ interface Conversation {
title: string; title: string;
classId: string | null; classId: string | null;
updatedAt: number; updatedAt: number;
running?: boolean;
} }
const ITEM_URL = { quiz: 'quizzes', deck: 'decks', note: 'notes', document: 'documents', class: 'classes', attempt: 'session' } as const; const ITEM_URL = { quiz: 'quizzes', deck: 'decks', note: 'notes', document: 'documents', class: 'classes', attempt: 'session' } as const;
@ -172,6 +173,82 @@ function AssistantMessage({ message, onNavigate, onAction }: { message: ChatMess
); );
} }
/* ------------------------------ composer: model picker and @ tags ------------------------------ */
const TAG_ICON: Record<TagKind, ReactNode> = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen />, document: <FileText />, folder: <Folder /> };
const TAG_NOUN: Record<TagKind, string> = { quiz: 'Quiz', deck: 'Flashcards', note: 'Note', document: 'Document', folder: 'Folder' };
function TagChip({ item, onRemove, inverted }: { item: TaggedItem; onRemove?: () => void; inverted?: boolean }) {
return (
<span className={cx('inline-flex h-6 max-w-full items-center gap-1 rounded-full pr-2 pl-1.5 text-xs font-medium [&>svg]:size-3 [&>svg]:shrink-0', inverted ? 'bg-paper/15 text-paper' : 'bg-accent-soft text-accent')}>
{TAG_ICON[item.kind]}
<span className="truncate">{item.title}</span>
{onRemove && (
<button type="button" aria-label={`Remove ${item.title}`} onClick={onRemove} className="-mr-1 grid size-4 place-items-center rounded-full hover:bg-accent/15">
<X className="size-3" />
</button>
)}
</span>
);
}
/** Model chooser for this chat. "Default" follows the Assistant model set in Settings. */
function ModelPicker({ value, onChange, defaultLabel }: { value: string; onChange: (id: string) => void; defaultLabel?: string }) {
const models = useAiModels();
const usable = (models.data ?? []).filter((m) => m.available);
const chosen = usable.find((m) => m.id === value);
const providers = [...new Set(usable.map((m) => m.providerName))];
return (
<Menu
align="start"
trigger={
<button type="button" className="flex max-w-full min-w-0 items-center gap-1 rounded-md text-xs text-ink-3 hover:text-ink" aria-label="Choose the model for this chat">
<span className="truncate">{chosen ? chosen.label : defaultLabel ? `${defaultLabel}` : 'Default model'}</span>
<ChevronDown className="size-3 shrink-0" />
</button>
}
>
<MenuLabel>Model for this chat</MenuLabel>
<MenuItem onSelect={() => onChange('')} hint={!chosen ? <Check className="size-3.5" /> : undefined}>
Default{defaultLabel ? ` · ${defaultLabel}` : ''}
</MenuItem>
{providers.map((p) => (
<div key={p}>
<MenuSeparator />
<MenuLabel>{p}</MenuLabel>
{usable
.filter((m) => m.providerName === p)
.map((m) => (
<MenuItem key={m.id} onSelect={() => onChange(m.id)} hint={m.id === value ? <Check className="size-3.5" /> : !m.capabilities.tools ? 'no tools' : undefined}>
{m.label}
</MenuItem>
))}
</div>
))}
</Menu>
);
}
/** Finds an "@query" being typed just before the caret. */
function mentionAt(text: string, caret: number): { start: number; query: string } | null {
const before = text.slice(0, caret);
const m = /(^|\s)@([^\s@]{0,40})$/.exec(before);
return m ? { start: caret - m[2].length - 1, query: m[2] } : null;
}
function useMentionables(classId: string | null, query: string, enabled: boolean) {
const debounced = useDebounced(query, 150);
// Inside a class: load its materials once and filter here. Elsewhere: search by title.
const q = useQuery({
queryKey: ['ai', 'mentionables', classId ?? '', classId ? '' : debounced],
queryFn: () => api.get<{ items: Mentionable[] }>(`/api/ai/mentionables?${new URLSearchParams(classId ? { classId } : { q: debounced })}`).then((r) => r.items),
enabled: enabled && (Boolean(classId) || debounced.length >= 1),
staleTime: 30_000,
});
const needle = query.toLowerCase();
return (q.data ?? []).filter((i) => !needle || i.title.toLowerCase().includes(needle) || (i.folderName ?? '').toLowerCase().includes(needle)).slice(0, 40);
}
/* ------------------------------ panel ------------------------------ */ /* ------------------------------ panel ------------------------------ */
export default function AssistantPanel({ export default function AssistantPanel({
@ -186,56 +263,166 @@ export default function AssistantPanel({
onConversationChange?: (id: string | null) => void; onConversationChange?: (id: string | null) => void;
}) { }) {
const ai = useAiStatus(); const ai = useAiStatus();
const models = useAiModels();
const classes = useClasses(); const classes = useClasses();
const refresh = useRefresh(); const refresh = useRefresh();
const qc = useQueryClient(); const qc = useQueryClient();
const { seed, context } = useAssistantState(); const { seed, context } = useAssistantState();
const [conversationId, setConversationId] = useState<string | null>(routeConversationId ?? null); const initialConversation = variant === 'page' ? (routeConversationId ?? null) : assistant.drawerConversation;
const [conversationId, setConversationId] = useState<string | null>(initialConversation);
const [messages, setMessages] = useState<ChatMessage[]>([]); const [messages, setMessages] = useState<ChatMessage[]>([]);
const [input, setInput] = useState(''); const [input, setInput] = useState('');
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
const [loadingHistory, setLoadingHistory] = useState(false); const [loadingHistory, setLoadingHistory] = useState(false);
const [focusDocs, setFocusDocs] = useState<string[]>([]); const [focusDocs, setFocusDocs] = useState<string[]>([]);
const abort = useRef<AbortController | null>(null); const [tags, setTags] = useState<TaggedItem[]>([]);
const [mention, setMention] = useState<{ start: number; query: string } | null>(null);
const [mentionIndex, setMentionIndex] = useState(0);
const [modelId, setModelId] = useLocalStorage('sd.assistant.model', '');
/** The connection to the running turn. Aborting it only detaches: the turn continues on the server. */
const stream = useRef<AbortController | null>(null);
const stopRequested = useRef(false);
const conversationRef = useRef<string | null>(initialConversation);
const scroller = useRef<HTMLDivElement>(null); const scroller = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLTextAreaElement>(null); const inputRef = useRef<HTMLTextAreaElement>(null);
const stick = useRef(true); const stick = useRef(true);
const handledSeed = useRef(0); const handledSeed = useRef(0);
const history = useQuery({ queryKey: ['ai', 'conversations'], queryFn: () => api.get<{ conversations: Conversation[] }>('/api/ai/conversations').then((r) => r.conversations), staleTime: 30_000 }); const history = useQuery({ queryKey: ['ai', 'conversations'], queryFn: () => api.get<{ conversations: Conversation[] }>('/api/ai/conversations').then((r) => r.conversations), staleTime: 30_000 });
const availableModel = (models.data ?? []).find((m) => m.id === modelId && m.available);
const effectiveModelId = availableModel ? modelId : '';
const load = useCallback(async (id: string) => { const setConversation = useCallback(
setLoadingHistory(true); (id: string | null) => {
try { conversationRef.current = id;
const res = await api.get<{ messages: ChatMessage[] }>(`/api/ai/conversations/${id}`);
setMessages(res.messages);
setConversationId(id); setConversationId(id);
stick.current = true; if (variant === 'drawer') assistant.rememberDrawerConversation(id);
} catch { },
setConversationId(null); [variant],
setMessages([]); );
} finally {
setLoadingHistory(false); /** Applies one streamed event to the pending assistant message. */
} const applyEvent = useCallback((pendingId: string, e: AssistantEvent) => {
const patch = (fn: (m: ChatMessage) => ChatMessage) => setMessages((list) => list.map((m) => (m.id === pendingId ? fn(m) : m)));
if (e.type === 'start') patch((m) => ({ ...m, model: e.model }));
else if (e.type === 'text') patch((m) => ({ ...m, text: m.text + e.delta }));
else if (e.type === 'reasoning') patch((m) => ({ ...m, reasoning: (m.reasoning ?? '') + e.delta }));
else if (e.type === 'tool') patch((m) => ({ ...m, tools: m.tools.some((t) => t.id === e.tool.id) ? m.tools.map((t) => (t.id === e.tool.id ? e.tool : t)) : [...m.tools, e.tool] }));
else if (e.type === 'ui') patch((m) => ({ ...m, ui: [...m.ui, e.item] }));
else if (e.type === 'error') patch((m) => ({ ...m, error: e.message }));
}, []);
/** Follows a turn (new or already running) until it finishes or this panel detaches. */
const follow = useCallback(
async (pendingId: string, run: (signal: AbortSignal, onEvent: (e: AssistantEvent) => void) => Promise<void>) => {
stream.current?.abort();
const controller = new AbortController();
stream.current = controller;
stopRequested.current = false;
setBusy(true);
let finished = false;
let startedId: string | null = null;
try {
await run(controller.signal, (e) => {
if (e.type === 'start') {
startedId = e.conversationId;
if (stopRequested.current) void api.post(`/api/ai/chat/${e.conversationId}/stop`).catch(() => undefined);
if (e.conversationId !== conversationRef.current) {
setConversation(e.conversationId);
onConversationChange?.(e.conversationId);
}
}
if (e.type === 'done') finished = true;
applyEvent(pendingId, e);
});
} catch (e) {
if ((e as Error)?.name !== 'AbortError') setMessages((list) => list.map((m) => (m.id === pendingId ? { ...m, error: errorMessage(e) } : m)));
} finally {
if (stream.current === controller) {
stream.current = null;
setBusy(false);
}
// Detached (left the conversation): leave the turn running and the message as it is.
if (finished || !controller.signal.aborted) {
setMessages((list) =>
list.map((m) =>
m.id === pendingId
? { ...m, pending: false, tools: m.tools.map((t) => (t.status === 'running' ? { ...t, status: 'error', summary: 'Stopped' } : t)), text: m.text || (m.error || m.ui.length || m.tools.length ? m.text : stopRequested.current ? '*(Stopped.)*' : m.text) }
: m,
),
);
void qc.invalidateQueries({ queryKey: ['ai', 'conversations'] });
// Tools may have created drafts, classes or sessions.
void refresh();
}
void startedId;
}
},
[applyEvent, onConversationChange, qc, refresh, setConversation],
);
const load = useCallback(
async (id: string) => {
stream.current?.abort();
setLoadingHistory(true);
try {
const res = await api.get<{ conversation: { id: string; running?: boolean }; messages: ChatMessage[] }>(`/api/ai/conversations/${id}`);
setConversation(id);
stick.current = true;
if (!res.conversation.running) {
setMessages(res.messages);
setBusy(false);
return;
}
// Still answering: show what is saved up to the question, then replay the live turn.
const lastUser = res.messages.map((m) => m.role).lastIndexOf('user');
const pendingId = `p${Date.now()}`;
setMessages([...res.messages.slice(0, lastUser + 1), { id: pendingId, role: 'assistant', text: '', tools: [], ui: [], createdAt: Date.now(), pending: true }]);
setLoadingHistory(false);
void follow(pendingId, (signal, onEvent) => streamEvents<AssistantEvent>(`/api/ai/chat/${id}/stream`, undefined, onEvent, signal));
} catch {
setConversation(null);
setMessages([]);
} finally {
setLoadingHistory(false);
}
},
[follow, setConversation],
);
// Open the remembered or routed conversation on mount.
useEffect(() => {
if (initialConversation) void load(initialConversation);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []); }, []);
useEffect(() => { useEffect(() => {
if (routeConversationId && routeConversationId !== conversationId) void load(routeConversationId); if (variant !== 'page') return;
if (!routeConversationId && variant === 'page' && conversationId && !busy) { if (routeConversationId && routeConversationId !== conversationRef.current) void load(routeConversationId);
setConversationId(null); if (!routeConversationId && conversationRef.current && !busy) {
setConversation(null);
setMessages([]); setMessages([]);
} }
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [routeConversationId]); }, [routeConversationId]);
const newChat = useCallback(() => { const newChat = useCallback(() => {
abort.current?.abort(); // Detach only: an answer still being written keeps going and is saved in its conversation.
setConversationId(null); stream.current?.abort();
setBusy(false);
setConversation(null);
setMessages([]); setMessages([]);
setFocusDocs([]); setFocusDocs([]);
setTags([]);
onConversationChange?.(null); onConversationChange?.(null);
setTimeout(() => inputRef.current?.focus(), 30); setTimeout(() => inputRef.current?.focus(), 30);
}, [onConversationChange]); }, [onConversationChange, setConversation]);
const stop = useCallback(() => {
stopRequested.current = true;
const id = conversationRef.current;
if (id) void api.post(`/api/ai/chat/${id}/stop`).catch(() => undefined);
}, []);
const activeDocs = focusDocs.length > 0 ? focusDocs : context.documentIds; const activeDocs = focusDocs.length > 0 ? focusDocs : context.documentIds;
const className = classes.data?.find((c) => c.id === context.classId)?.name; const className = classes.data?.find((c) => c.id === context.classId)?.name;
@ -244,47 +431,37 @@ export default function AssistantPanel({
async (text: string, opts: { conversationId?: string | null; documentIds?: string[]; classId?: string | null } = {}) => { async (text: string, opts: { conversationId?: string | null; documentIds?: string[]; classId?: string | null } = {}) => {
const message = text.trim(); const message = text.trim();
if (!message || busy) return; if (!message || busy) return;
const convo = opts.conversationId !== undefined ? opts.conversationId : conversationId; const convo = opts.conversationId !== undefined ? opts.conversationId : conversationRef.current;
setBusy(true); const sentTags = tags;
setInput(''); setInput('');
setTags([]);
setMention(null);
stick.current = true; stick.current = true;
const pendingId = `p${Date.now()}`; const pendingId = `p${Date.now()}`;
setMessages((m) => [...m, { id: `u${Date.now()}`, role: 'user', text: message, tools: [], ui: [], createdAt: Date.now() }, { id: pendingId, role: 'assistant', text: '', tools: [], ui: [], createdAt: Date.now(), pending: true }]); setMessages((m) => [
const patch = (fn: (m: ChatMessage) => ChatMessage) => setMessages((list) => list.map((m) => (m.id === pendingId ? fn(m) : m))); ...m,
const controller = new AbortController(); { id: `u${Date.now()}`, role: 'user', text: message, tags: sentTags.length ? sentTags : undefined, tools: [], ui: [], createdAt: Date.now() },
abort.current = controller; { id: pendingId, role: 'assistant', text: '', tools: [], ui: [], createdAt: Date.now(), pending: true },
let newId: string | null = null; ]);
try { await follow(pendingId, (signal, onEvent) =>
await streamEvents<AssistantEvent>( streamEvents<AssistantEvent>(
'/api/ai/chat', '/api/ai/chat',
{ conversationId: convo, message, context: { classId: opts.classId !== undefined ? opts.classId : context.classId, documentIds: opts.documentIds ?? activeDocs } }, {
(e) => { conversationId: convo,
if (e.type === 'start') { message,
newId = e.conversationId; modelId: effectiveModelId || undefined,
patch((m) => ({ ...m, model: e.model })); context: {
} else if (e.type === 'text') patch((m) => ({ ...m, text: m.text + e.delta })); classId: opts.classId !== undefined ? opts.classId : context.classId,
else if (e.type === 'reasoning') patch((m) => ({ ...m, reasoning: (m.reasoning ?? '') + e.delta })); documentIds: opts.documentIds ?? activeDocs,
else if (e.type === 'tool') patch((m) => ({ ...m, tools: m.tools.some((t) => t.id === e.tool.id) ? m.tools.map((t) => (t.id === e.tool.id ? e.tool : t)) : [...m.tools, e.tool] })); items: sentTags.map((t) => ({ kind: t.kind, id: t.id })),
else if (e.type === 'ui') patch((m) => ({ ...m, ui: [...m.ui, e.item] })); },
else if (e.type === 'error') patch((m) => ({ ...m, error: e.message }));
}, },
controller.signal, onEvent,
); signal,
} catch (e) { ),
if ((e as Error)?.name !== 'AbortError') patch((m) => ({ ...m, error: errorMessage(e) })); );
} finally {
patch((m) => ({ ...m, pending: false, tools: m.tools.map((t) => (t.status === 'running' ? { ...t, status: 'error', summary: 'Stopped' } : t)), text: m.text || (m.error || m.ui.length || m.tools.length ? m.text : controller.signal.aborted ? '*(Stopped.)*' : m.text) }));
setBusy(false);
if (newId && newId !== convo) {
setConversationId(newId);
onConversationChange?.(newId);
}
void qc.invalidateQueries({ queryKey: ['ai', 'conversations'] });
// Tools may have created drafts, classes or sessions.
void refresh();
}
}, },
[busy, conversationId, context.classId, activeDocs, onConversationChange, qc, refresh], [busy, tags, follow, effectiveModelId, context.classId, activeDocs],
); );
// Requests from elsewhere in the app ("Ask about this document", "New questions on these topics"). // Requests from elsewhere in the app ("Ask about this document", "New questions on these topics").
@ -293,8 +470,9 @@ export default function AssistantPanel({
handledSeed.current = seed.id; handledSeed.current = seed.id;
assistant.consumeSeed(); assistant.consumeSeed();
if (seed.newChat) { if (seed.newChat) {
abort.current?.abort(); stream.current?.abort();
setConversationId(null); setBusy(false);
setConversation(null);
setMessages([]); setMessages([]);
onConversationChange?.(null); onConversationChange?.(null);
} }
@ -304,14 +482,15 @@ export default function AssistantPanel({
if (seed.prompt) setInput(seed.prompt); if (seed.prompt) setInput(seed.prompt);
setTimeout(() => inputRef.current?.focus(), 60); setTimeout(() => inputRef.current?.focus(), 60);
} }
}, [seed, ai.data, send, onConversationChange]); }, [seed, ai.data, send, onConversationChange, setConversation]);
// Keep the newest content in view unless the user has scrolled up to read. // Keep the newest content in view unless the user has scrolled up to read.
useEffect(() => { useEffect(() => {
const el = scroller.current; const el = scroller.current;
if (el && stick.current) el.scrollTop = el.scrollHeight; if (el && stick.current) el.scrollTop = el.scrollHeight;
}, [messages]); }, [messages]);
useEffect(() => () => abort.current?.abort(), []); // Leaving only disconnects; the server finishes the answer and saves it.
useEffect(() => () => stream.current?.abort(), []);
const updateAction = (actionId: string, status: string, result: string) => { const updateAction = (actionId: string, status: string, result: string) => {
setMessages((list) => list.map((m) => ({ ...m, ui: m.ui.map((u) => (u.type === 'action' && u.actionId === actionId ? { ...u, status: status as typeof u.status, result } : u)) }))); setMessages((list) => list.map((m) => ({ ...m, ui: m.ui.map((u) => (u.type === 'action' && u.actionId === actionId ? { ...u, status: status as typeof u.status, result } : u)) })));
@ -329,16 +508,54 @@ export default function AssistantPanel({
}, [activeDocs.length, className]); }, [activeDocs.length, className]);
const contextLabel = activeDocs.length > 0 ? (context.documentIds.length && context.label ? context.label : plural(activeDocs.length, 'document')) : className; const contextLabel = activeDocs.length > 0 ? (context.documentIds.length && context.label ? context.label : plural(activeDocs.length, 'document')) : className;
const options = useMentionables(context.classId, mention?.query ?? '', mention !== null);
const pickable = options.filter((o) => !tags.some((t) => t.kind === o.kind && t.id === o.id));
const updateMention = (text: string, caret: number) => {
const next = mentionAt(text, caret);
setMention(next);
if (!next || next.query !== mention?.query) setMentionIndex(0);
};
const choose = (item: Mentionable) => {
setTags((t) => (t.some((x) => x.kind === item.kind && x.id === item.id) ? t : [...t, { kind: item.kind, id: item.id, title: item.title }]));
if (mention) {
const caret = inputRef.current?.selectionStart ?? input.length;
const next = `${input.slice(0, mention.start)}${input.slice(caret)}`.replace(/\s{2,}/g, ' ');
setInput(next);
setTimeout(() => {
const el = inputRef.current;
if (el) {
el.focus();
el.setSelectionRange(mention.start, mention.start);
}
}, 0);
}
setMention(null);
};
const openPicker = () => {
const el = inputRef.current;
const caret = el?.selectionStart ?? input.length;
const needsSpace = caret > 0 && !/\s/.test(input[caret - 1] ?? '');
const next = `${input.slice(0, caret)}${needsSpace ? ' ' : ''}@${input.slice(caret)}`;
setInput(next);
const at = caret + (needsSpace ? 1 : 0) + 1;
setMention({ start: at - 1, query: '' });
setMentionIndex(0);
setTimeout(() => {
el?.focus();
el?.setSelectionRange(at, at);
}, 0);
};
return ( return (
<div className="flex min-h-0 flex-1 flex-col"> <div className="flex min-h-0 flex-1 flex-col">
<header className={cx('flex h-14 shrink-0 items-center gap-2 border-b border-line px-3', variant === 'page' && 'lg:px-0')}> <header className={cx('flex h-14 shrink-0 items-center gap-2 border-b border-line px-3', variant === 'page' && 'lg:px-5')}>
<span className="grid size-8 place-items-center rounded-[10px] bg-ink text-marker"> <span className="grid size-8 shrink-0 place-items-center rounded-[10px] bg-ink text-marker">
<Sparkles className="size-4" /> <Sparkles className="size-4" />
</span> </span>
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<div className="text-sm font-semibold">Assistant</div> <div className="text-sm font-semibold">Assistant</div>
<div className="truncate text-xs text-ink-3">{ai.data?.resolved.chat ? ai.data.resolved.chat.label : ai.data && !ai.data.ready ? 'Not set up' : ''}</div> {ai.data?.ready ? <ModelPicker value={effectiveModelId} onChange={setModelId} defaultLabel={ai.data.resolved.chat?.label} /> : <div className="truncate text-xs text-ink-3">{ai.data ? 'Not set up' : ''}</div>}
</div> </div>
<IconButton label="New chat" size="sm" onClick={newChat}> <IconButton label="New chat" size="sm" onClick={newChat}>
<Plus /> <Plus />
@ -354,7 +571,7 @@ export default function AssistantPanel({
<MenuLabel>Recent conversations</MenuLabel> <MenuLabel>Recent conversations</MenuLabel>
{(history.data ?? []).length === 0 && <div className="px-2.5 py-2 text-[13px] text-ink-3">Nothing yet</div>} {(history.data ?? []).length === 0 && <div className="px-2.5 py-2 text-[13px] text-ink-3">Nothing yet</div>}
{(history.data ?? []).slice(0, 12).map((c) => ( {(history.data ?? []).slice(0, 12).map((c) => (
<MenuItem key={c.id} onSelect={() => load(c.id)} hint={timeAgo(c.updatedAt)}> <MenuItem key={c.id} onSelect={() => load(c.id)} hint={c.running ? 'working…' : timeAgo(c.updatedAt)}>
{c.title} {c.title}
</MenuItem> </MenuItem>
))} ))}
@ -365,7 +582,9 @@ export default function AssistantPanel({
icon={<Trash2 />} icon={<Trash2 />}
danger danger
onSelect={async () => { onSelect={async () => {
await api.del(`/api/ai/conversations/${conversationId}`).catch(() => undefined); const id = conversationId;
stop();
await api.del(`/api/ai/conversations/${id}`).catch(() => undefined);
void qc.invalidateQueries({ queryKey: ['ai', 'conversations'] }); void qc.invalidateQueries({ queryKey: ['ai', 'conversations'] });
newChat(); newChat();
}} }}
@ -385,7 +604,7 @@ export default function AssistantPanel({
const el = e.currentTarget; const el = e.currentTarget;
stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80; stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80;
}} }}
className={cx('min-h-0 flex-1 overflow-y-auto px-4 py-5', variant === 'page' && 'lg:px-1')} className={cx('min-h-0 flex-1 overflow-y-auto px-4 py-5', variant === 'page' && 'lg:px-6')}
aria-live="polite" aria-live="polite"
> >
{ai.isLoading || loadingHistory ? ( {ai.isLoading || loadingHistory ? (
@ -395,18 +614,18 @@ export default function AssistantPanel({
) : !ai.data?.ready ? ( ) : !ai.data?.ready ? (
<div className="mx-auto max-w-sm pt-8"> <div className="mx-auto max-w-sm pt-8">
<Callout tone="accent" icon={<Sparkles />} title="Connect an AI model to use the assistant"> <Callout tone="accent" icon={<Sparkles />} title="Connect an AI model to use the assistant">
Add a provider such as OpenAI, Anthropic, Google Gemini or a local model, then switch on a model. Add a provider such as OpenAI, Anthropic, Google Gemini, DeepSeek or a local model, then switch on a model.
<div className="mt-3"> <div className="mt-3">
<Button to="/settings/ai" onClick={() => variant === 'drawer' && assistant.close()} size="sm" variant="primary"> <Button to="/settings/ai" onClick={() => variant === 'drawer' && assistant.close()} size="sm" variant="primary">
Open AI settings Open AI settings
</Button> </Button>
</div> </div>
</Callout> </Callout>
</div> </div>
) : messages.length === 0 ? ( ) : messages.length === 0 ? (
<div className="mx-auto flex h-full max-w-md flex-col justify-center pb-6"> <div className="mx-auto flex h-full max-w-md flex-col justify-center pb-6">
<h2 className="display text-[26px]">What are we working on?</h2> <h2 className="display text-[26px]">What are we working on?</h2>
<p className="mt-1.5 text-sm text-ink-2">I can read your documents, look at your results, and prepare quizzes, flashcards and study guides for you to review.</p> <p className="mt-1.5 text-sm text-ink-2">I can read your documents, look at your results, and prepare quizzes, flashcards and study guides for you to review. Type @ to point me at a specific quiz, deck, note or document.</p>
<div className="mt-5 space-y-2"> <div className="mt-5 space-y-2">
{suggestions.map((s) => ( {suggestions.map((s) => (
<button key={s} type="button" onClick={() => send(s)} className="group flex w-full items-center gap-3 rounded-[13px] border border-line bg-surface px-3.5 py-2.5 text-left text-sm shadow-1 hover:border-ink-3"> <button key={s} type="button" onClick={() => send(s)} className="group flex w-full items-center gap-3 rounded-[13px] border border-line bg-surface px-3.5 py-2.5 text-left text-sm shadow-1 hover:border-ink-3">
@ -421,7 +640,16 @@ export default function AssistantPanel({
{messages.map((m) => {messages.map((m) =>
m.role === 'user' ? ( m.role === 'user' ? (
<div key={m.id} className="flex justify-end"> <div key={m.id} className="flex justify-end">
<div className="max-w-[88%] rounded-[16px] rounded-br-md bg-ink px-3.5 py-2.5 text-[15px] whitespace-pre-wrap text-paper">{m.text}</div> <div className="max-w-[88%] rounded-[16px] rounded-br-md bg-ink px-3.5 py-2.5 text-[15px] whitespace-pre-wrap text-paper">
{m.tags?.length ? (
<div className="mb-1.5 flex flex-wrap gap-1">
{m.tags.map((t) => (
<TagChip key={`${t.kind}:${t.id}`} item={t} inverted />
))}
</div>
) : null}
{m.text}
</div>
</div> </div>
) : ( ) : (
<AssistantMessage key={m.id} message={m} onNavigate={() => variant === 'drawer' && window.innerWidth < 1360 && assistant.close()} onAction={updateAction} /> <AssistantMessage key={m.id} message={m} onNavigate={() => variant === 'drawer' && window.innerWidth < 1360 && assistant.close()} onAction={updateAction} />
@ -432,8 +660,8 @@ export default function AssistantPanel({
</div> </div>
{ai.data?.ready && ( {ai.data?.ready && (
<div className={cx('safe-bottom shrink-0 border-t border-line px-3 pt-2.5 pb-3', variant === 'page' && 'lg:px-0')}> <div className={cx('safe-pb-3 shrink-0 border-t border-line px-3 pt-2.5', variant === 'page' && 'lg:px-6')}>
<div className="mx-auto max-w-2xl"> <div className="relative mx-auto max-w-2xl">
{contextLabel && ( {contextLabel && (
<div className="mb-2 flex items-center gap-1.5"> <div className="mb-2 flex items-center gap-1.5">
<Badge tone="accent" className="max-w-full"> <Badge tone="accent" className="max-w-full">
@ -447,41 +675,104 @@ export default function AssistantPanel({
)} )}
</div> </div>
)} )}
{mention && (
<div role="listbox" aria-label="Tag a material" className="absolute inset-x-0 bottom-full z-30 mb-2 max-h-72 overflow-y-auto rounded-xl border border-line bg-surface p-1.5 shadow-2">
<div className="eyebrow px-2 pt-1 pb-1.5">{context.classId ? `Materials in ${className ?? 'this class'}` : 'Your library'}</div>
{pickable.length === 0 ? (
<div className="px-2.5 py-2 text-[13px] text-ink-3">{context.classId || mention.query ? 'Nothing matches.' : 'Type to search your quizzes, decks, notes and documents.'}</div>
) : (
pickable.map((o, i) => (
<button
key={`${o.kind}:${o.id}`}
type="button"
role="option"
aria-selected={i === mentionIndex}
onMouseDown={(e) => e.preventDefault()}
onMouseMove={() => setMentionIndex(i)}
onClick={() => choose(o)}
className={cx('flex w-full items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left', i === mentionIndex && 'bg-ink/7')}
>
<span className="grid size-7 shrink-0 place-items-center rounded-md bg-sunken text-ink-2 [&>svg]:size-3.5">{TAG_ICON[o.kind]}</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-sm">{o.title}</span>
<span className="block truncate text-[11px] text-ink-3">
{TAG_NOUN[o.kind]}
{o.folderName ? ` · ${o.folderName}` : ''}
{!context.classId ? ` · ${o.className}` : ''}
</span>
</span>
</button>
))
)}
</div>
)}
<form <form
className="flex items-end gap-2 rounded-[16px] border border-line-strong bg-surface p-1.5 shadow-1 focus-within:border-accent focus-within:ring-2 focus-within:ring-accent/20" className="rounded-[16px] border border-line-strong bg-surface p-1.5 shadow-1 focus-within:border-accent focus-within:ring-2 focus-within:ring-accent/20"
onSubmit={(e) => { onSubmit={(e) => {
e.preventDefault(); e.preventDefault();
if (busy) abort.current?.abort(); if (busy) stop();
else void send(input); else void send(input);
}} }}
> >
<textarea {tags.length > 0 && (
ref={inputRef} <div className="flex flex-wrap gap-1 px-1.5 pt-1 pb-1.5">
value={input} {tags.map((t) => (
rows={1} <TagChip key={`${t.kind}:${t.id}`} item={t} onRemove={() => setTags((list) => list.filter((x) => !(x.kind === t.kind && x.id === t.id)))} />
onChange={(e) => { ))}
setInput(e.target.value); </div>
e.target.style.height = 'auto'; )}
e.target.style.height = `${Math.min(e.target.scrollHeight, 180)}px`; <div className="flex items-end gap-1.5">
}} <textarea
onKeyDown={(e) => { ref={inputRef}
if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) { value={input}
e.preventDefault(); rows={1}
if (!busy) void send(input); onChange={(e) => {
} setInput(e.target.value);
}} updateMention(e.target.value, e.target.selectionStart ?? e.target.value.length);
placeholder="Ask anything, or describe what to create…" e.target.style.height = 'auto';
aria-label="Message the assistant" e.target.style.height = `${Math.min(e.target.scrollHeight, 180)}px`;
className="max-h-44 min-h-9 flex-1 resize-none bg-transparent px-2.5 py-1.5 text-[15px] outline-none placeholder:text-ink-3" }}
/> onSelect={(e) => mention && updateMention(e.currentTarget.value, e.currentTarget.selectionStart ?? 0)}
<button onBlur={() => setTimeout(() => setMention(null), 120)}
type="submit" onKeyDown={(e) => {
disabled={!busy && !input.trim()} if (mention && pickable.length > 0) {
aria-label={busy ? 'Stop' : 'Send'} if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
className={cx('grid size-9 shrink-0 place-items-center rounded-[11px] transition-colors disabled:opacity-35', busy ? 'bg-sunken text-ink' : 'bg-ink text-paper hover:bg-ink/85')} e.preventDefault();
> setMentionIndex((i) => (i + (e.key === 'ArrowDown' ? 1 : -1) + pickable.length) % pickable.length);
{busy ? <Square className="size-3.5 fill-current" /> : <ArrowUp className="size-[18px]" />} return;
</button> }
if (e.key === 'Enter' || e.key === 'Tab') {
e.preventDefault();
choose(pickable[Math.min(mentionIndex, pickable.length - 1)]);
return;
}
}
if (mention && e.key === 'Escape') {
e.preventDefault();
setMention(null);
return;
}
if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
e.preventDefault();
if (!busy) void send(input);
}
}}
placeholder={context.classId ? 'Ask anything. Type @ to tag a quiz, deck, note or document…' : 'Ask anything, or describe what to create…'}
aria-label="Message the assistant"
className="max-h-44 min-h-9 flex-1 resize-none bg-transparent px-2.5 py-1.5 text-[15px] outline-none placeholder:text-ink-3"
/>
<IconButton label="Tag a material" size="sm" className="mb-0.5" onClick={openPicker}>
<AtSign />
</IconButton>
<button
type="submit"
disabled={!busy && !input.trim()}
aria-label={busy ? 'Stop' : 'Send'}
className={cx('grid size-9 shrink-0 place-items-center rounded-[11px] transition-colors disabled:opacity-35', busy ? 'bg-sunken text-ink' : 'bg-ink text-paper hover:bg-ink/85')}
>
{busy ? <Square className="size-3.5 fill-current" /> : <ArrowUp className="size-[18px]" />}
</button>
</div>
</form> </form>
<p className="mt-1.5 px-1 text-[11px] text-ink-3">Drafts and changes always wait for your approval. AI can make mistakes: verify clinical facts.</p> <p className="mt-1.5 px-1 text-[11px] text-ink-3">Drafts and changes always wait for your approval. AI can make mistakes: verify clinical facts.</p>
</div> </div>

View file

@ -0,0 +1,114 @@
import { useQuery } from '@tanstack/react-query';
import { BookOpen, CircleAlert, Layers, NotebookPen, Sparkles } from 'lucide-react';
import { useEffect, useRef } from 'react';
import { NavLink, useNavigate } from 'react-router';
import { toast } from 'sonner';
import { api } from '@/lib/api';
import { qk, useRefresh } from '@/lib/queries';
import type { DraftSummary } from '@/lib/types';
import { cx, plural, timeAgo } from '@/lib/util';
import { ProgressBar } from '@/ui';
const ICON = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen /> };
const NOUN = { quiz: 'quiz', deck: 'flashcards', note: 'study guide' };
/**
* Drafts that still need attention: generations in progress (polled while running), drafts
* ready for review, and recent failures. Generation runs on the server, so leaving the page
* never loses it; this is how you get back to it.
*/
export function useOpenDrafts() {
const q = useQuery({
queryKey: qk.drafts,
queryFn: ({ signal }) => api.get<{ drafts: DraftSummary[] }>('/api/drafts', signal).then((r) => r.drafts),
refetchInterval: (query) => (query.state.data?.some((d) => d.status === 'generating') ? 2000 : 60_000),
});
const dayAgo = Date.now() - 86_400_000;
const drafts = (q.data ?? []).filter((d) => d.status === 'generating' || d.status === 'ready' || (d.status === 'failed' && d.updatedAt > dayAgo));
return { drafts, generating: drafts.filter((d) => d.status === 'generating') };
}
/** Announces generations that finish while you are elsewhere in the app. */
export function useDraftNotifications() {
const { drafts } = useOpenDrafts();
const refresh = useRefresh();
const navigate = useNavigate();
const seen = useRef<Map<string, string>>(new Map());
useEffect(() => {
const prev = seen.current;
for (const d of drafts) {
const before = prev.get(d.id);
if (before === 'generating' && d.status !== 'generating') {
const onPage = window.location.pathname === `/drafts/${d.id}`;
if (!onPage) {
if (d.status === 'ready') toast.success(`${d.title || 'Your draft'} is ready to review`, { action: { label: 'Review', onClick: () => navigate(`/drafts/${d.id}`) } });
else toast.error(`${d.title || 'A draft'} did not finish`);
}
void refresh(qk.drafts);
}
}
seen.current = new Map(drafts.map((d) => [d.id, d.status]));
}, [drafts, refresh, navigate]);
}
function DraftRow({ d, compact }: { d: DraftSummary; compact?: boolean }) {
const status =
d.status === 'generating'
? d.progressLabel || 'Starting'
: d.status === 'failed'
? 'Did not finish'
: d.kind === 'note'
? 'Ready to review'
: `Ready · ${plural(d.itemCount, d.kind === 'quiz' ? 'question' : 'card')}`;
return (
<NavLink
to={`/drafts/${d.id}`}
className={({ isActive }) => cx('block rounded-[9px] px-2.5 py-2 transition-colors', isActive ? 'bg-ink/8' : 'hover:bg-ink/5', !compact && 'border border-line bg-surface shadow-1')}
>
<span className="flex items-center gap-2">
<span className={cx('grid shrink-0 place-items-center [&>svg]:size-3.5', d.status === 'failed' ? 'text-bad' : d.status === 'generating' ? 'text-accent' : 'text-ink-3')}>
{d.status === 'failed' ? <CircleAlert /> : d.status === 'generating' ? <Sparkles className="animate-pulse" /> : ICON[d.kind]}
</span>
<span className="min-w-0 flex-1 truncate text-[13px] font-medium">{d.title || `New ${NOUN[d.kind]}`}</span>
{!compact && <span className="shrink-0 text-[11px] text-ink-3">{timeAgo(d.updatedAt)}</span>}
</span>
<span className={cx('mt-0.5 block truncate pl-[22px] text-[11px]', d.status === 'failed' ? 'text-bad' : 'text-ink-3')}>{status}</span>
{d.status === 'generating' && <ProgressBar value={Math.max(0.04, d.progress)} className="mt-1.5 ml-[22px] h-1" label={`Generating ${d.title}`} />}
</NavLink>
);
}
/** Sidebar section: only shown while something is generating or waiting for review. */
export function SidebarDrafts() {
const { drafts } = useOpenDrafts();
if (drafts.length === 0) return null;
return (
<div className="mt-5 px-3">
<div className="mb-1.5 flex items-center justify-between px-2">
<span className="eyebrow">Drafts</span>
{drafts.length > 5 && <span className="text-[11px] text-ink-3">{drafts.length}</span>}
</div>
<div className="max-h-56 space-y-0.5 overflow-y-auto">
{drafts.slice(0, 8).map((d) => (
<DraftRow key={d.id} d={d} compact />
))}
</div>
</div>
);
}
/** The same list for the Today page, where phones see it. */
export function DraftsSection() {
const { drafts } = useOpenDrafts();
if (drafts.length === 0) return null;
return (
<section className="mb-8">
<h2 className="eyebrow mb-3">Drafts</h2>
<div className="grid gap-2 sm:grid-cols-2">
{drafts.slice(0, 6).map((d) => (
<DraftRow key={d.id} d={d} />
))}
</div>
</section>
);
}

View file

@ -86,6 +86,8 @@ function LlmInstructionsDialog({ open, onClose }: { open: boolean; onClose: () =
setCopied(true); setCopied(true);
toast.success('Instructions copied'); toast.success('Instructions copied');
setTimeout(() => setCopied(false), 2000); setTimeout(() => setCopied(false), 2000);
} else {
toast.error('Your browser blocked copying. Select the text and copy it yourself.');
} }
}} }}
> >
@ -269,7 +271,7 @@ export function ImportDialog({ open, onClose, classId, folderId }: { open: boole
<Button size="sm" icon={<FileUp />} onClick={() => fileRef.current?.click()}> <Button size="sm" icon={<FileUp />} onClick={() => fileRef.current?.click()}>
Choose file Choose file
</Button> </Button>
<span>{filename ? filename : 'or drop a .json, .txt or .csv file here. Study Desk V1 exports work too.'}</span> <span>{filename ? filename : 'or drop a .json, .txt or .csv file here.'}</span>
</div> </div>
</div> </div>

View file

@ -15,8 +15,11 @@ interface EmbeddingStatus {
running: boolean; running: boolean;
lastError: string; lastError: string;
defaults: Record<ProviderKind, string | null>; defaults: Record<ProviderKind, string | null>;
local: { model: string; label: string; dimensions: number; downloaded: boolean; status: 'idle' | 'loading' | 'ready' | 'error'; error: string; enabledByDefault: boolean };
} }
const LOCAL = 'local';
const KEY = ['ai', 'embeddings']; const KEY = ['ai', 'embeddings'];
/** /**
@ -33,7 +36,8 @@ export function SemanticSettings({ providers }: { providers: Provider[] }) {
refetchInterval: (query) => (query.state.data?.running ? 1500 : false), refetchInterval: (query) => (query.state.data?.running ? 1500 : false),
}); });
const data = q.data; const data = q.data;
const eligible = providers.filter((p) => p.kind !== 'anthropic' && p.enabled); // Anthropic and DeepSeek have no embeddings API.
const eligible = providers.filter((p) => p.kind !== 'anthropic' && p.kind !== 'deepseek' && p.enabled);
const [providerId, setProviderId] = useState(''); const [providerId, setProviderId] = useState('');
const [model, setModel] = useState(''); const [model, setModel] = useState('');
const [dimensions, setDimensions] = useState(''); const [dimensions, setDimensions] = useState('');
@ -47,9 +51,10 @@ export function SemanticSettings({ providers }: { providers: Provider[] }) {
}, [data]); }, [data]);
if (!data) return null; if (!data) return null;
const isLocal = providerId === LOCAL;
const chosen = providers.find((p) => p.id === providerId); const chosen = providers.find((p) => p.id === providerId);
const suggested = chosen ? data.defaults[chosen.kind] : null; const suggested = isLocal ? data.local.label : chosen ? data.defaults[chosen.kind] : null;
const dirty = providerId !== (data.settings.providerId ?? '') || model.trim() !== data.settings.model || dimensions !== (data.settings.dimensions ? String(data.settings.dimensions) : ''); const dirty = providerId !== (data.settings.providerId ?? '') || (!isLocal && (model.trim() !== data.settings.model || dimensions !== (data.settings.dimensions ? String(data.settings.dimensions) : '')));
const reload = () => qc.invalidateQueries({ queryKey: KEY }); const reload = () => qc.invalidateQueries({ queryKey: KEY });
const save = async () => { const save = async () => {
@ -59,7 +64,7 @@ export function SemanticSettings({ providers }: { providers: Provider[] }) {
} }
setBusy('save'); setBusy('save');
try { try {
await api.put('/api/ai/embeddings', { providerId: providerId || null, model: providerId ? model.trim() : '', dimensions: dimensions ? Number(dimensions) : null }); await api.put('/api/ai/embeddings', { providerId: providerId || null, model: providerId && !isLocal ? model.trim() : '', dimensions: dimensions && !isLocal ? Number(dimensions) : null });
toast.success(providerId ? 'Semantic search is on. Indexing your documents…' : 'Semantic search is off'); toast.success(providerId ? 'Semantic search is on. Indexing your documents…' : 'Semantic search is off');
await reload(); await reload();
} catch (e) { } catch (e) {
@ -103,11 +108,7 @@ export function SemanticSettings({ providers }: { providers: Provider[] }) {
Finds passages by meaning as well as by words, so "why do patients on Lasix need bananas?" finds the section on furosemide and potassium. Used by search, the assistant and Finds passages by meaning as well as by words, so "why do patients on Lasix need bananas?" finds the section on furosemide and potassium. Used by search, the assistant and
focused generation. Keyword search keeps working without it. focused generation. Keyword search keeps working without it.
</p> </p>
{eligible.length === 0 ? ( {(
<Callout tone="accent" icon={<Sparkles />} className="mt-4" title="Needs an embeddings provider">
Connect OpenAI, Gemini, Ollama or an OpenAI-compatible server above. Anthropic does not offer embeddings.
</Callout>
) : (
<div className="mt-4 grid gap-3 sm:grid-cols-[1fr_1fr_auto]"> <div className="mt-4 grid gap-3 sm:grid-cols-[1fr_1fr_auto]">
<Field label="Provider"> <Field label="Provider">
<Select <Select
@ -115,10 +116,12 @@ export function SemanticSettings({ providers }: { providers: Provider[] }) {
onChange={(e) => { onChange={(e) => {
const next = providers.find((p) => p.id === e.target.value); const next = providers.find((p) => p.id === e.target.value);
setProviderId(e.target.value); setProviderId(e.target.value);
if (next && (!model || !dirty)) setModel(data.defaults[next.kind] ?? ''); if (e.target.value === LOCAL) setModel(data.local.model);
else if (next && (!model || !dirty || model === data.local.model)) setModel(data.defaults[next.kind] ?? '');
}} }}
> >
<option value="">Off (keywords only)</option> <option value="">Off (keywords only)</option>
<option value={LOCAL}>Built-in model (free, runs on this server)</option>
{eligible.map((p) => ( {eligible.map((p) => (
<option key={p.id} value={p.id}> <option key={p.id} value={p.id}>
{p.name} {p.name}
@ -127,16 +130,29 @@ export function SemanticSettings({ providers }: { providers: Provider[] }) {
</Select> </Select>
</Field> </Field>
<Field label="Embedding model" hint={suggested ? `Suggested: ${suggested}` : chosen ? 'The model id your server uses for embeddings' : undefined}> <Field label="Embedding model" hint={suggested ? `Suggested: ${suggested}` : chosen ? 'The model id your server uses for embeddings' : undefined}>
<Input value={model} onChange={(e) => setModel(e.target.value)} placeholder={suggested || 'text-embedding-3-small'} disabled={!providerId} /> <Input value={isLocal ? data.local.label : model} onChange={(e) => setModel(e.target.value)} placeholder={suggested || 'text-embedding-3-small'} disabled={!providerId || isLocal} />
</Field> </Field>
<Field label="Size" hint="Optional"> <Field label="Size" hint="Optional">
<Input type="number" min={64} max={4096} step={64} value={dimensions} onChange={(e) => setDimensions(e.target.value)} placeholder="Native" disabled={!providerId} className="sm:w-28" /> <Input type="number" min={64} max={4096} step={64} value={isLocal ? String(data.local.dimensions) : dimensions} onChange={(e) => setDimensions(e.target.value)} placeholder="Native" disabled={!providerId || isLocal} className="sm:w-28" />
</Field> </Field>
</div> </div>
)} )}
{eligible.length > 0 && ( {isLocal && (
<p className="mt-2 text-[13px] text-ink-3">
{data.local.downloaded
? 'The model is on this server. Embeddings are computed on its processor at no cost.'
: 'The model (about 35 MB) is downloaded from Hugging Face the first time it is used, then kept with your data. Embeddings are computed on this server at no cost.'}
{data.local.status === 'loading' ? ' Loading the model now…' : ''}
</p>
)}
{eligible.length === 0 && !isLocal && (
<Callout tone="accent" icon={<Sparkles />} className="mt-3" title="Cloud embeddings need a provider">
Use the built-in model, or connect OpenAI, Gemini, Ollama or an OpenAI-compatible server above. Anthropic and DeepSeek do not offer embeddings.
</Callout>
)}
{(
<div className="mt-3 flex flex-wrap gap-2"> <div className="mt-3 flex flex-wrap gap-2">
<Button variant="primary" size="sm" disabled={!dirty || (Boolean(providerId) && !model.trim())} loading={busy === 'save'} onClick={save}> <Button variant="primary" size="sm" disabled={!dirty || (Boolean(providerId) && !isLocal && !model.trim())} loading={busy === 'save'} onClick={save}>
Save Save
</Button> </Button>
{data.configured && !dirty && ( {data.configured && !dirty && (
@ -174,7 +190,7 @@ export function SemanticSettings({ providers }: { providers: Provider[] }) {
</div> </div>
)} )}
</div> </div>
<p className="mt-2 text-xs text-ink-3">Embedding costs are small (OpenAI's small model is about $0.02 per million tokens) and appear in Usage. Local Ollama models are free.</p> <p className="mt-2 text-xs text-ink-3">The built-in model and local Ollama models are free. Cloud embedding costs are small (OpenAI's small model is about $0.02 per million tokens) and appear in Usage.</p>
</Section> </Section>
); );
} }

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)} />
</>
);
}

View file

@ -150,7 +150,7 @@ export function ForecastBars({ values, className }: { values: number[]; classNam
/** Horizontal accuracy bar with the percentage. */ /** Horizontal accuracy bar with the percentage. */
export function AccuracyBar({ value, className }: { value: number; className?: string }) { export function AccuracyBar({ value, className }: { value: number; className?: string }) {
const p = Math.round(value * 100); const p = Math.round(value * 100);
const tone = p >= 80 ? 'bg-good' : p >= 60 ? 'bg-warn' : 'bg-bad'; const tone = p >= 85 ? 'bg-good' : p >= 77 ? 'bg-warn' : 'bg-bad';
return ( return (
<div className={cx('flex items-center gap-2', className)}> <div className={cx('flex items-center gap-2', className)}>
<div className="h-1.5 flex-1 overflow-hidden rounded-full bg-ink/8"> <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-ink/8">

View file

@ -280,8 +280,8 @@ const SHARE_BLURB: Record<ShareKind, string> = {
deck: 'Anyone with the link can study these flashcards. They cannot change them.', deck: 'Anyone with the link can study these flashcards. They cannot change them.',
note: 'Anyone with the link can read this note.', note: 'Anyone with the link can read this note.',
document: 'Anyone with the link can view and download this file.', document: 'Anyone with the link can view and download this file.',
folder: 'Anyone with the link can study the quizzes, decks and notes in this folder. Uploaded documents are not included.', folder: 'Anyone with the link can study the quizzes, decks and notes in this folder and view or download its documents.',
class: 'Anyone with the link can study every quiz, deck and note in this class. Uploaded documents are not included.', class: 'Anyone with the link can study every quiz, deck and note in this class and view or download its documents.',
}; };
export function ShareDialog({ target, onClose }: { target: { kind: ShareKind; id: string; title: string } | null; onClose: () => void }) { export function ShareDialog({ target, onClose }: { target: { kind: ShareKind; id: string; title: string } | null; onClose: () => void }) {
@ -321,6 +321,8 @@ export function ShareDialog({ target, onClose }: { target: { kind: ShareKind; id
setCopied(true); setCopied(true);
toast.success('Link copied'); toast.success('Link copied');
setTimeout(() => setCopied(false), 2000); setTimeout(() => setCopied(false), 2000);
} else {
toast.error('Your browser blocked copying. Select the link and copy it yourself.');
} }
}; };
const on = Boolean(share?.enabled); const on = Boolean(share?.enabled);

View file

@ -1,7 +1,7 @@
import { Check, ImagePlus, MessageSquareText, Plus, Trash2 } from 'lucide-react'; import { Check, ImagePlus, MessageSquareText, Plus, Trash2 } from 'lucide-react';
import { useRef, useState, type ReactNode } from 'react'; import { useRef, useState, type ReactNode } from 'react';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { DIFFICULTIES, LIMITS, optionLetter, type DraftCard, type DraftQuestion, type Issue, type QuestionType } from '@shared/content'; import { DIFFICULTIES, LIMITS, optionLetter, parseNumericAnswer, type DraftCard, type DraftQuestion, type Issue, type QuestionType } from '@shared/content';
import { api, errorMessage } from '@/lib/api'; import { api, errorMessage } from '@/lib/api';
import { cx } from '@/lib/util'; import { cx } from '@/lib/util';
import { IconButton, Input, Segmented, Select, Textarea } from '@/ui'; import { IconButton, Input, Segmented, Select, Textarea } from '@/ui';
@ -157,6 +157,19 @@ export function QuestionEditor({
}; };
const setType = (type: QuestionType) => { const setType = (type: QuestionType) => {
if (type === value.type) return;
if (type === 'numeric') {
// Keep any marked answer that already is a number; otherwise start with one blank answer.
const keep = value.options.filter((o) => o.correct && parseNumericAnswer(o.text) !== null).map((o) => ({ ...o, correct: true }));
set({ type, options: keep.length ? keep : [{ text: '', correct: true, why: value.options.find((o) => o.correct)?.why ?? '' }] });
return;
}
if (value.type === 'numeric') {
const options = value.options.filter((o) => o.text.trim()).map((o, i) => ({ ...o, correct: type === 'multi' || i === 0 }));
while (options.length < 4) options.push({ text: '', correct: false, why: '' });
set({ type, options });
return;
}
if (type === 'single') { if (type === 'single') {
// Keep only the first marked answer so the question stays valid. // Keep only the first marked answer so the question stays valid.
let seen = false; let seen = false;
@ -178,9 +191,11 @@ export function QuestionEditor({
label="Question type" label="Question type"
value={value.type} value={value.type}
onChange={setType} onChange={setType}
className="max-w-full overflow-x-auto"
options={[ options={[
{ value: 'single', label: 'Multiple choice' }, { value: 'single', label: 'Multiple choice' },
{ value: 'multi', label: 'Select all that apply' }, { value: 'multi', label: 'Select all' },
{ value: 'numeric', label: 'Numeric answer' },
]} ]}
/> />
</div> </div>
@ -190,6 +205,41 @@ export function QuestionEditor({
<MarkdownArea label="Question text" value={value.stem} onChange={(stem) => set({ stem })} placeholder="A client with heart failure reports…" rows={2} serif autoFocus={autoFocus} invalid={has('stem')} /> <MarkdownArea label="Question text" value={value.stem} onChange={(stem) => set({ stem })} placeholder="A client with heart failure reports…" rows={2} serif autoFocus={autoFocus} invalid={has('stem')} />
</div> </div>
{value.type === 'numeric' ? (
<div>
<FieldLabel>Correct answer</FieldLabel>
<ul className="space-y-2">
{value.options.map((o, i) => (
<li key={i} className="flex items-start gap-2">
<Input
value={o.text}
onChange={(e) => setOption(i, { text: e.target.value, correct: true })}
aria-label={i === 0 ? 'Correct answer' : `Also accepted ${i}`}
aria-invalid={Boolean(o.text.trim()) && parseNumericAnswer(o.text) === null}
placeholder={i === 0 ? '12.5 mL' : 'Another accepted answer'}
inputMode="decimal"
className="num max-w-xs"
/>
{value.options.length > 1 && (
<IconButton label="Remove this answer" size="sm" className="mt-1" onClick={() => set({ options: value.options.filter((_, k) => k !== i) })}>
<Trash2 />
</IconButton>
)}
</li>
))}
</ul>
<p className="mt-1.5 text-[13px] text-ink-3">The student types a number. Units are ignored, so "12.5" and "12.5 mL" both count. Add a tolerance with ±, for example "12.5 ± 0.1 mL".</p>
{value.options.length < LIMITS.options && (
<button type="button" onClick={() => set({ options: [...value.options, { text: '', correct: true, why: '' }] })} className="mt-1 inline-flex h-8 items-center gap-1.5 rounded-lg px-2 text-[13px] font-medium text-accent hover:bg-accent-soft">
<Plus className="size-4" /> Accept another answer
</button>
)}
<div className="mt-3">
<FieldLabel>Working</FieldLabel>
<Textarea autoGrow rows={1} value={value.options[0]?.why ?? ''} onChange={(e) => setOption(0, { why: e.target.value })} aria-label="Working" placeholder="How the answer is calculated (optional)" className="bg-sunken text-[13px]" />
</div>
</div>
) : (
<div> <div>
<FieldLabel>{value.type === 'single' ? 'Answer choices · mark the correct one' : 'Answer choices · mark every correct one'}</FieldLabel> <FieldLabel>{value.type === 'single' ? 'Answer choices · mark the correct one' : 'Answer choices · mark every correct one'}</FieldLabel>
<ul className="space-y-2"> <ul className="space-y-2">
@ -230,6 +280,7 @@ export function QuestionEditor({
</button> </button>
)} )}
</div> </div>
)}
<div> <div>
<FieldLabel>Rationale</FieldLabel> <FieldLabel>Rationale</FieldLabel>

View file

@ -2,7 +2,7 @@ import { ArrowLeft, Check, Lightbulb, RotateCcw, Shuffle, SkipForward, X } from
import { useCallback, useEffect, useId, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react'; import { useCallback, useEffect, useId, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react';
import { cx, plural, shuffle, useHotkeys } from '@/lib/util'; import { cx, plural, shuffle, useHotkeys } from '@/lib/util';
import { Markdown } from '@/ui/Markdown'; import { Markdown } from '@/ui/Markdown';
import { Button, IconButton, Kbd, ProgressBar } from '@/ui'; import { Button, IconButton, ProgressBar } from '@/ui';
import { Ring } from './charts'; import { Ring } from './charts';
/* ------------------------------ streaks ------------------------------ */ /* ------------------------------ streaks ------------------------------ */
@ -163,7 +163,7 @@ export function FlipCard({
<div className={cx(face, 'flip-front')} inert={flipped ? true : undefined}> <div className={cx(face, 'flip-front')} inert={flipped ? true : undefined}>
<div className="flex items-center justify-between px-6 pt-5"> <div className="flex items-center justify-between px-6 pt-5">
<span className="eyebrow">{label ?? 'Question'}</span> <span className="eyebrow">{label ?? 'Question'}</span>
<span className="text-xs text-ink-3">Click or press Space to flip</span> <span className="text-xs text-ink-3">Tap the card to flip it</span>
</div> </div>
<div className="grid flex-1 place-items-center px-7 py-6 sm:px-12 lg:px-16"> <div className="grid flex-1 place-items-center px-7 py-6 sm:px-12 lg:px-16">
<Markdown serif className={cx('max-h-[52vh] w-full overflow-y-auto', size(front))}> <Markdown serif className={cx('max-h-[52vh] w-full overflow-y-auto', size(front))}>
@ -238,18 +238,6 @@ export function StudyFooter({ children }: { children: ReactNode }) {
); );
} }
export function KeyHints({ items }: { items: [ReactNode, string][] }) {
return (
<div className="mt-2 hidden flex-wrap justify-center gap-x-4 gap-y-1 text-[11px] text-ink-3 md:flex">
{items.map(([keys, label]) => (
<span key={label} className="flex items-center gap-1">
{keys} {label}
</span>
))}
</div>
);
}
const SWIPE_MS = 230; const SWIPE_MS = 230;
/* ------------------------------ browse / cram ------------------------------ */ /* ------------------------------ browse / cram ------------------------------ */
@ -433,7 +421,7 @@ export function CramSession({
{!done && card && ( {!done && card && (
<StudyFooter> <StudyFooter>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<IconButton label="Previous card (Backspace)" onClick={() => move(-1)} disabled={state.index === 0 || busy}> <IconButton label="Previous card" onClick={() => move(-1)} disabled={state.index === 0 || busy}>
<ArrowLeft /> <ArrowLeft />
</IconButton> </IconButton>
{seenAnswer ? ( {seenAnswer ? (
@ -450,17 +438,10 @@ export function CramSession({
Show answer Show answer
</Button> </Button>
)} )}
<IconButton label="Skip card (S)" onClick={() => move(1)} disabled={busy}> <IconButton label="Skip card" onClick={() => move(1)} disabled={busy}>
<SkipForward /> <SkipForward />
</IconButton> </IconButton>
</div> </div>
<KeyHints
items={[
[<><Kbd>Space</Kbd><Kbd>↑</Kbd><Kbd>↓</Kbd></>, 'flip'],
[<Kbd>←</Kbd>, 'still learning'],
[<Kbd>→</Kbd>, 'know it'],
]}
/>
</StudyFooter> </StudyFooter>
)} )}
</div> </div>

View file

@ -1,10 +1,10 @@
import { ArrowLeft, ArrowRight, Check, CircleCheck, CircleX, Clock, Flag, LayoutGrid, RotateCcw, X } from 'lucide-react'; import { ArrowLeft, ArrowRight, Check, CircleCheck, CircleX, Clock, Flag, LayoutGrid, RotateCcw, X } from 'lucide-react';
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { isFullyCorrect, optionLetter, scoreQuestion, type SataScoring } from '@shared/content'; import { isFullyCorrect, letterGrade, optionLetter, parseNumericAnswer, scoreQuestion, type SataScoring } from '@shared/content';
import type { AnswerState, SnapshotQuestion } from '@/lib/types'; import type { AnswerState, SnapshotQuestion } from '@/lib/types';
import { cx, formatDuration, formatMinutes, plural, useHotkeys, useLatest } from '@/lib/util'; import { cx, formatDuration, formatMinutes, plural, useHotkeys, useLatest } from '@/lib/util';
import { Markdown } from '@/ui/Markdown'; import { Markdown } from '@/ui/Markdown';
import { Badge, Button, Dialog, IconButton, Kbd, ProgressBar, Segmented, useConfirm } from '@/ui'; import { Badge, Button, Dialog, IconButton, Input, ProgressBar, Segmented, useConfirm } from '@/ui';
import { Ring } from './charts'; import { Ring } from './charts';
/* ------------------------------ option list ------------------------------ */ /* ------------------------------ option list ------------------------------ */
@ -71,6 +71,87 @@ function OptionList({
); );
} }
/* ------------------------------ numeric answer ------------------------------ */
/** The accepted answer(s) of a numeric question, for display. */
function acceptedAnswers(question: SnapshotQuestion): string {
return question.options
.filter((o) => o.correct !== false)
.map((o) => o.text)
.join(' or ');
}
/** A calculation: the student types the number. Units are optional; only the number is checked. */
function NumericAnswer({
question,
value,
revealed,
onChange,
onSubmit,
autoFocus,
}: {
question: SnapshotQuestion;
value: string;
revealed: boolean;
onChange?: (text: string) => void;
onSubmit?: () => void;
autoFocus?: boolean;
}) {
const right = revealed && isFullyCorrect(scoreQuestion(question, value ? [value] : []));
const unreadable = value.trim() !== '' && parseNumericAnswer(value) === null;
const why = question.options.find((o) => o.why)?.why;
return (
<div className="space-y-2.5">
<label className="block">
<span className="sr-only">Your answer</span>
<Input
value={value}
autoFocus={autoFocus}
inputMode="decimal"
autoComplete="off"
spellCheck={false}
readOnly={revealed || !onChange}
onChange={(e) => onChange?.(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.nativeEvent.isComposing) {
e.preventDefault();
onSubmit?.();
}
}}
placeholder="Type your answer, e.g. 12.5"
aria-invalid={unreadable || undefined}
className={cx(
'num h-14 max-w-sm rounded-[14px] px-4 text-[20px]',
revealed && (right ? 'border-good bg-good-soft ring-1 ring-good' : 'border-bad bg-bad-soft ring-1 ring-bad'),
)}
/>
</label>
{!revealed && <p className="text-[13px] text-ink-3">{unreadable ? 'Enter a number. Units are optional.' : 'Only the number is checked, so units are optional.'}</p>}
{revealed && (
<div className="rounded-[14px] border border-good/60 border-dashed px-3.5 py-2.5">
<div className="flex flex-wrap items-baseline gap-x-2 text-[15px]">
<span className="text-[13px] font-medium text-good">Correct answer</span>
<span className="num font-semibold">{acceptedAnswers(question)}</span>
</div>
{why && <div className="mt-1 text-[13.5px] leading-snug text-ink-2">{why}</div>}
</div>
)}
</div>
);
}
/** What the student answered, as text (for the AI explanation). */
function answerTexts(question: SnapshotQuestion, selected: string[]): string[] {
if (question.type === 'numeric') return selected.slice(0, 1);
return question.options.filter((o) => selected.includes(o.id)).map((o) => o.text);
}
/** Tone for a percentage on the 7-point scale: A and B good, C passing, D and F failing. */
export function gradeToneFor(percent: number): 'good' | 'warn' | 'bad' {
const letter = letterGrade(percent);
return letter === 'A' || letter === 'B' ? 'good' : letter === 'C' ? 'warn' : 'bad';
}
/** "2 of 3" style credit for a select-all question, so partial credit is never a mystery. */ /** "2 of 3" style credit for a select-all question, so partial credit is never a mystery. */
function creditDetail(question: SnapshotQuestion, selected: string[], sata: SataScoring): string | null { function creditDetail(question: SnapshotQuestion, selected: string[], sata: SataScoring): string | null {
if (question.type !== 'multi') return null; if (question.type !== 'multi') return null;
@ -194,12 +275,21 @@ export function QuizRunner(p: RunnerProps) {
topRef.current?.scrollIntoView({ block: 'start' }); topRef.current?.scrollIntoView({ block: 'start' });
}, [index]); }, [index]);
const numeric = question.type === 'numeric';
const toggle = (id: string) => { const toggle = (id: string) => {
if (checked) return; if (checked || numeric) return;
const next = question.type === 'single' ? [id] : selected.includes(id) ? selected.filter((x) => x !== id) : [...selected, id]; const next = question.type === 'single' ? [id] : selected.includes(id) ? selected.filter((x) => x !== id) : [...selected, id];
p.onAnswer(question.id, next, false); p.onAnswer(question.id, next, false);
}; };
const check = () => selected.length > 0 && p.onAnswer(question.id, selected, true); const typed = numeric ? (selected[0] ?? '') : '';
const setTyped = (text: string) => !checked && p.onAnswer(question.id, text.trim() ? [text] : [], false);
const canCheck = numeric ? parseNumericAnswer(typed) !== null : selected.length > 0;
const check = () => {
if (!canCheck) return;
// Let the typed answer show its correct/incorrect colour instead of the focus ring.
if (numeric) (document.activeElement as HTMLElement | null)?.blur();
p.onAnswer(question.id, numeric ? [typed.trim()] : selected, true);
};
const go = (i: number) => p.onIndex(Math.max(0, Math.min(total - 1, i))); const go = (i: number) => p.onIndex(Math.max(0, Math.min(total - 1, i)));
const toggleFlag = () => p.onFlags(flagged ? p.flags.filter((f) => f !== question.id) : [...p.flags, question.id]); const toggleFlag = () => p.onFlags(flagged ? p.flags.filter((f) => f !== question.id) : [...p.flags, question.id]);
@ -223,8 +313,8 @@ export function QuizRunner(p: RunnerProps) {
}; };
useHotkeys({ useHotkeys({
...Object.fromEntries(question.options.map((o, i) => [String(i + 1), () => toggle(o.id)])), ...(numeric ? {} : Object.fromEntries(question.options.map((o, i) => [String(i + 1), () => toggle(o.id)]))),
...Object.fromEntries(question.options.map((o, i) => [optionLetter(i).toLowerCase(), () => toggle(o.id)])), ...(numeric ? {} : Object.fromEntries(question.options.map((o, i) => [optionLetter(i).toLowerCase(), () => toggle(o.id)]))),
Enter: primary, Enter: primary,
ArrowRight: () => go(index + 1), ArrowRight: () => go(index + 1),
ArrowLeft: () => go(index - 1), ArrowLeft: () => go(index - 1),
@ -253,7 +343,7 @@ export function QuizRunner(p: RunnerProps) {
</div> </div>
{live && ( {live && (
<div <div
className={cx('num flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[13px] font-semibold', live.percent >= 80 ? 'bg-good-soft text-good' : live.percent >= 60 ? 'bg-warn-soft text-warn' : 'bg-bad-soft text-bad')} className={cx('num flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[13px] font-semibold', { good: 'bg-good-soft text-good', warn: 'bg-warn-soft text-warn', bad: 'bg-bad-soft text-bad' }[gradeToneFor(live.percent)])}
aria-label={`Score so far: ${fmtPoints(live.points)} of ${live.n} correct, ${live.percent} percent`} aria-label={`Score so far: ${fmtPoints(live.points)} of ${live.n} correct, ${live.percent} percent`}
> >
<span className="hidden sm:inline"> <span className="hidden sm:inline">
@ -262,10 +352,13 @@ export function QuizRunner(p: RunnerProps) {
{live.percent}% {live.percent}%
</div> </div>
)} )}
<div className={cx('num flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[13px] font-medium', remaining !== null && remaining < 60 ? 'bg-bad-soft text-bad' : 'text-ink-2')} aria-label={remaining !== null ? 'Time remaining' : 'Time elapsed'}> {/* The clock is a timed-exam feature; untimed sessions track time quietly for the results. */}
<Clock className="size-3.5" /> {remaining !== null && (
{formatDuration(remaining ?? clock)} <div className={cx('num flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[13px] font-medium', remaining < 60 ? 'bg-bad-soft text-bad' : 'text-ink-2')} aria-label="Time remaining">
</div> <Clock className="size-3.5" />
{formatDuration(remaining)}
</div>
)}
<button type="button" onClick={() => setNavOpen(true)} className="num flex h-9 items-center gap-1.5 rounded-[9px] border border-line-strong bg-surface px-2.5 text-[13px] font-medium shadow-1 hover:border-ink-3" aria-label="Question navigator"> <button type="button" onClick={() => setNavOpen(true)} className="num flex h-9 items-center gap-1.5 rounded-[9px] border border-line-strong bg-surface px-2.5 text-[13px] font-medium shadow-1 hover:border-ink-3" aria-label="Question navigator">
<LayoutGrid className="size-3.5 text-ink-3" /> <LayoutGrid className="size-3.5 text-ink-3" />
{index + 1}/{total} {index + 1}/{total}
@ -289,8 +382,12 @@ export function QuizRunner(p: RunnerProps) {
<Markdown serif className="text-[20px] leading-[1.45] sm:text-[22px]"> <Markdown serif className="text-[20px] leading-[1.45] sm:text-[22px]">
{question.stem} {question.stem}
</Markdown> </Markdown>
<p className="mt-3 mb-4 text-[13px] font-medium text-ink-3">{question.type === 'multi' ? 'Select all that apply.' : 'Choose one answer.'}</p> <p className="mt-3 mb-4 text-[13px] font-medium text-ink-3">{question.type === 'multi' ? 'Select all that apply.' : numeric ? 'Enter your answer.' : 'Choose one answer.'}</p>
<OptionList question={question} selected={selected} revealed={checked} onToggle={toggle} /> {numeric ? (
<NumericAnswer key={question.id} question={question} value={typed} revealed={checked} onChange={setTyped} onSubmit={primary} />
) : (
<OptionList question={question} selected={selected} revealed={checked} onToggle={toggle} />
)}
{checked && ( {checked && (
<div className="mt-5 animate-in space-y-4"> <div className="mt-5 animate-in space-y-4">
@ -301,10 +398,7 @@ export function QuizRunner(p: RunnerProps) {
<Markdown className="text-[15px]">{question.rationale}</Markdown> <Markdown className="text-[15px]">{question.rationale}</Markdown>
</div> </div>
)} )}
{p.renderExtra?.( {p.renderExtra?.(question, answerTexts(question, selected))}
question,
question.options.filter((o) => selected.includes(o.id)).map((o) => o.text),
)}
</div> </div>
)} )}
</div> </div>
@ -324,11 +418,8 @@ export function QuizRunner(p: RunnerProps) {
<Button size="lg" variant="ghost" onClick={() => (isLast ? requestFinish() : go(index + 1))}> <Button size="lg" variant="ghost" onClick={() => (isLast ? requestFinish() : go(index + 1))}>
{isLast ? 'Finish' : 'Skip'} {isLast ? 'Finish' : 'Skip'}
</Button> </Button>
<Button size="lg" variant="primary" disabled={selected.length === 0} onClick={check} className="min-w-32"> <Button size="lg" variant="primary" disabled={!canCheck} onClick={check} className="min-w-32">
Check Check
<span className="hidden sm:inline">
<Kbd>↵</Kbd>
</span>
</Button> </Button>
</> </>
) : isLast ? ( ) : isLast ? (
@ -361,7 +452,8 @@ export function QuizRunner(p: RunnerProps) {
</Button> </Button>
} }
> >
<div className="grid grid-cols-6 gap-2 sm:grid-cols-8"> {/* Padding keeps the current-question ring (and its offset) inside the scroll area. */}
<div className="grid grid-cols-6 gap-2 p-1.5 sm:grid-cols-8">
{p.questions.map((q, i) => { {p.questions.map((q, i) => {
const s = statusOf(q); const s = statusOf(q);
return ( return (
@ -383,21 +475,6 @@ export function QuizRunner(p: RunnerProps) {
); );
})} })}
</div> </div>
<div className="mt-5 hidden flex-wrap gap-x-4 gap-y-2 text-xs text-ink-3 sm:flex">
<span className="flex items-center gap-1.5">
<Kbd>1</Kbd>–<Kbd>9</Kbd> or <Kbd>A</Kbd>–<Kbd>E</Kbd> choose
</span>
<span className="flex items-center gap-1.5">
<Kbd>Enter</Kbd> check / next
</span>
<span className="flex items-center gap-1.5">
<Kbd>←</Kbd>
<Kbd>→</Kbd> move
</span>
<span className="flex items-center gap-1.5">
<Kbd>M</Kbd> flag
</span>
</div>
</Dialog> </Dialog>
</div> </div>
); );
@ -440,7 +517,8 @@ export function QuizResults(p: ResultsProps) {
const partial = scored.filter((r) => !r.correct && r.score > 0).length; const partial = scored.filter((r) => !r.correct && r.score > 0).length;
const wrong = scored.length - right - partial; const wrong = scored.length - right - partial;
const skipped = rows.length - scored.length; const skipped = rows.length - scored.length;
const tone = percent >= 80 ? 'good' : percent >= 60 ? 'warn' : 'bad'; const tone = gradeToneFor(percent);
const grade = letterGrade(percent);
const topics = useMemo(() => { const topics = useMemo(() => {
const map = new Map<string, { n: number; s: number }>(); const map = new Map<string, { n: number; s: number }>();
@ -455,7 +533,7 @@ export function QuizResults(p: ResultsProps) {
}, [scored]); }, [scored]);
const visible = rows.filter((r) => (filter === 'all' ? true : filter === 'wrong' ? r.scored && !r.correct : p.flags.includes(r.q.id))); const visible = rows.filter((r) => (filter === 'all' ? true : filter === 'wrong' ? r.scored && !r.correct : p.flags.includes(r.q.id)));
const headline = percent >= 90 ? 'Excellent work' : percent >= 80 ? 'Strong result' : percent >= 60 ? 'Getting there' : 'Worth another pass'; const headline = { A: 'Excellent work', B: 'Strong result', C: 'Passing', D: 'Just below passing', F: 'Worth another pass' }[grade];
return ( return (
<div className="min-h-dvh bg-paper"> <div className="min-h-dvh bg-paper">
@ -471,13 +549,13 @@ export function QuizResults(p: ResultsProps) {
<section className="card p-6 sm:p-8"> <section className="card p-6 sm:p-8">
<div className="flex flex-col items-center gap-6 text-center sm:flex-row sm:text-left"> <div className="flex flex-col items-center gap-6 text-center sm:flex-row sm:text-left">
<Ring value={percent / 100} size={128} stroke={11} tone={tone}> <Ring value={percent / 100} size={128} stroke={11} tone={tone}>
<div className="leading-none"> <div className="flex flex-col items-center leading-none">
<span className="display num text-[38px] font-medium">{percent}</span> <span className="display text-[40px] font-medium">{grade}</span>
<span className="text-lg text-ink-3">%</span> <span className="num mt-1 text-[13px] font-medium text-ink-3">{percent}%</span>
</div> </div>
</Ring> </Ring>
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<div className="eyebrow mb-1">{p.mode === 'exam' ? 'Exam result' : 'Practice result'}</div> <div className="eyebrow mb-1">{p.mode === 'exam' ? 'Exam result' : 'Practice result'} · grade {grade}</div>
<h1 className="display text-[30px]">{headline}</h1> <h1 className="display text-[30px]">{headline}</h1>
<p className="mt-1.5 text-[15px] text-ink-2"> <p className="mt-1.5 text-[15px] text-ink-2">
<span className="num font-semibold text-ink">{fmtPoints(points)}</span> of <span className="num font-semibold text-ink">{scored.length}</span> points <span className="num font-semibold text-ink">{fmtPoints(points)}</span> of <span className="num font-semibold text-ink">{scored.length}</span> points
@ -506,7 +584,7 @@ export function QuizResults(p: ResultsProps) {
<span className="min-w-0 flex-1 truncate text-sm font-medium">{t.topic}</span> <span className="min-w-0 flex-1 truncate text-sm font-medium">{t.topic}</span>
<span className="text-xs text-ink-3">{plural(t.n, 'question')}</span> <span className="text-xs text-ink-3">{plural(t.n, 'question')}</span>
<div className="h-1.5 w-24 overflow-hidden rounded-full bg-ink/8 sm:w-36"> <div className="h-1.5 w-24 overflow-hidden rounded-full bg-ink/8 sm:w-36">
<div className={cx('h-full rounded-full', pc >= 80 ? 'bg-good' : pc >= 60 ? 'bg-warn' : 'bg-bad')} style={{ width: `${Math.max(4, pc)}%` }} /> <div className={cx('h-full rounded-full', { good: 'bg-good', warn: 'bg-warn', bad: 'bg-bad' }[gradeToneFor(pc)])} style={{ width: `${Math.max(4, pc)}%` }} />
</div> </div>
<span className="num w-10 text-right text-[13px] font-medium">{pc}%</span> <span className="num w-10 text-right text-[13px] font-medium">{pc}%</span>
</div> </div>
@ -550,7 +628,7 @@ export function QuizResults(p: ResultsProps) {
<Markdown serif className="mb-3.5 text-[17px]"> <Markdown serif className="mb-3.5 text-[17px]">
{r.q.stem} {r.q.stem}
</Markdown> </Markdown>
<OptionList question={r.q} selected={r.selected} revealed /> {r.q.type === 'numeric' ? <NumericAnswer question={r.q} value={r.selected[0] ?? ''} revealed /> : <OptionList question={r.q} selected={r.selected} revealed />}
{r.scored && !r.correct && r.answered && creditDetail(r.q, r.selected, p.sataScoring) && <p className="mt-2.5 text-[13px] text-ink-2">{creditDetail(r.q, r.selected, p.sataScoring)}</p>} {r.scored && !r.correct && r.answered && creditDetail(r.q, r.selected, p.sataScoring) && <p className="mt-2.5 text-[13px] text-ink-2">{creditDetail(r.q, r.selected, p.sataScoring)}</p>}
{r.q.rationale && ( {r.q.rationale && (
<div className="mt-3.5 rounded-xl bg-sunken px-4 py-3"> <div className="mt-3.5 rounded-xl bg-sunken px-4 py-3">
@ -560,10 +638,7 @@ export function QuizResults(p: ResultsProps) {
)} )}
{p.renderExtra && ( {p.renderExtra && (
<div className="mt-3"> <div className="mt-3">
{p.renderExtra( {p.renderExtra(r.q, answerTexts(r.q, r.selected))}
r.q,
r.q.options.filter((o) => r.selected.includes(o.id)).map((o) => o.text),
)}
</div> </div>
)} )}
</li> </li>

View file

@ -105,13 +105,13 @@ export function uploadWithProgress<T>(url: string, form: FormData, onProgress: (
}); });
} }
/** POSTs JSON and reads a server-sent event stream of JSON objects. */ /** POSTs JSON (or GETs, when `body` is undefined) and reads a server-sent event stream of JSON objects. */
export async function streamEvents<T extends { type: string }>(url: string, body: unknown, onEvent: (event: T) => void, signal?: AbortSignal): Promise<void> { export async function streamEvents<T extends { type: string }>(url: string, body: unknown, onEvent: (event: T) => void, signal?: AbortSignal): Promise<void> {
const res = await fetch(url, { const res = await fetch(url, {
method: 'POST', method: body === undefined ? 'GET' : 'POST',
credentials: 'same-origin', credentials: 'same-origin',
headers: { ...BASE_HEADERS, 'Content-Type': 'application/json', Accept: 'text/event-stream' }, headers: body === undefined ? { ...BASE_HEADERS, Accept: 'text/event-stream' } : { ...BASE_HEADERS, 'Content-Type': 'application/json', Accept: 'text/event-stream' },
body: JSON.stringify(body), body: body === undefined ? undefined : JSON.stringify(body),
signal, signal,
}); });
if (!res.ok || !res.body) { if (!res.ok || !res.body) {

View file

@ -23,6 +23,8 @@ const set = (patch: Partial<State>) => {
listeners.forEach((fn) => fn()); listeners.forEach((fn) => fn());
}; };
let seedId = 0; let seedId = 0;
/** The drawer's conversation, kept while the drawer is closed so reopening continues it. */
let drawerConversation: string | null = null;
export const assistant = { export const assistant = {
/** Opens the assistant, optionally with a prepared prompt. */ /** Opens the assistant, optionally with a prepared prompt. */
@ -39,6 +41,12 @@ export const assistant = {
consumeSeed() { consumeSeed() {
if (state.seed) set({ seed: null }); if (state.seed) set({ seed: null });
}, },
get drawerConversation() {
return drawerConversation;
},
rememberDrawerConversation(id: string | null) {
drawerConversation = id;
},
setContext(context: State['context']) { setContext(context: State['context']) {
const cur = state.context; const cur = state.context;
if (cur.classId === context.classId && cur.label === context.label && cur.documentIds.join() === context.documentIds.join()) return; if (cur.classId === context.classId && cur.label === context.label && cur.documentIds.join() === context.documentIds.join()) return;

View file

@ -339,7 +339,7 @@ export interface ShareListItem extends Share {
/* ------------------------------ AI ------------------------------ */ /* ------------------------------ AI ------------------------------ */
export type ProviderKind = 'openai' | 'anthropic' | 'gemini' | 'openai_compatible' | 'ollama'; export type ProviderKind = 'openai' | 'anthropic' | 'gemini' | 'deepseek' | 'openai_compatible' | 'ollama';
export interface AdapterMeta { export interface AdapterMeta {
kind: ProviderKind; kind: ProviderKind;
label: string; label: string;
@ -386,12 +386,26 @@ export interface AiModel {
maxOutput: number | null; maxOutput: number | null;
priceIn: number | null; priceIn: number | null;
priceOut: number | null; priceOut: number | null;
/** USD per million cached input tokens; null = the provider's usual cache discount. */
priceCachedIn: number | null;
} }
export type TaskName = 'chat' | 'generate' | 'vision' | 'quick'; export type TaskName = 'chat' | 'generate' | 'vision' | 'quick';
/** Reasoning effort levels, lowest to highest. Each provider maps them onto what it accepts. */
export const REASONING_EFFORTS = [
{ value: 'none', label: 'Off' },
{ value: 'minimal', label: 'Minimal' },
{ value: 'low', label: 'Low' },
{ value: 'medium', label: 'Medium' },
{ value: 'high', label: 'High' },
{ value: 'xhigh', label: 'Extra high' },
{ value: 'max', label: 'Max' },
] as const;
export type ReasoningEffort = (typeof REASONING_EFFORTS)[number]['value'];
export interface TaskConfig { export interface TaskConfig {
modelId: string | null; modelId: string | null;
temperature: number | null; temperature: number | null;
reasoningEffort: 'none' | 'low' | 'medium' | 'high' | null; reasoningEffort: ReasoningEffort | null;
maxOutputTokens: number | null; maxOutputTokens: number | null;
} }
export type TaskSettings = Record<TaskName | 'default', TaskConfig>; export type TaskSettings = Record<TaskName | 'default', TaskConfig>;
@ -444,10 +458,22 @@ export interface ToolActivity {
status: 'running' | 'done' | 'error'; status: 'running' | 'done' | 'error';
summary?: string; summary?: string;
} }
export type TagKind = 'quiz' | 'deck' | 'note' | 'document' | 'folder';
export interface TaggedItem {
kind: TagKind;
id: string;
title: string;
}
export interface Mentionable extends TaggedItem {
className: string;
classColor: string;
folderName?: string;
}
export interface ChatMessage { export interface ChatMessage {
id: number | string; id: number | string;
role: 'user' | 'assistant'; role: 'user' | 'assistant';
text: string; text: string;
tags?: TaggedItem[];
tools: ToolActivity[]; tools: ToolActivity[];
ui: UiItem[]; ui: UiItem[];
model?: string; model?: string;
@ -472,6 +498,8 @@ export interface Template {
description: string; description: string;
payload: Record<string, any>; payload: Record<string, any>;
builtin: boolean; builtin: boolean;
/** A built-in template the user has changed. */
edited?: boolean;
updatedAt: number; updatedAt: number;
} }
@ -514,6 +542,6 @@ export interface PublicCollection {
description?: string; description?: string;
color: ClassColor; color: ClassColor;
folders: { id: string; name: string }[]; folders: { id: string; name: string }[];
items: { kind: 'quiz' | 'deck' | 'note'; id: string; title: string; description: string; folderId: string | null; count: number }[]; items: { kind: 'quiz' | 'deck' | 'note' | 'document'; id: string; title: string; description: string; folderId: string | null; count: number }[];
} }
export type PublicPayload = PublicQuiz | PublicDeck | PublicNote | PublicDocument | PublicCollection; export type PublicPayload = PublicQuiz | PublicDeck | PublicNote | PublicDocument | PublicCollection;

View file

@ -72,10 +72,12 @@ export function formatCost(n: number | null | undefined): string {
return `$${n.toFixed(2)}`; return `$${n.toFixed(2)}`;
} }
/** Tone on the 7-point scale: A/B (85+) good, C (77-84) passing, D/F failing. */
export function gradeTone(percent: number | null): 'good' | 'warn' | 'bad' | 'none' { export function gradeTone(percent: number | null): 'good' | 'warn' | 'bad' | 'none' {
if (percent === null) return 'none'; if (percent === null) return 'none';
if (percent >= 80) return 'good'; const p = Math.round(percent);
if (percent >= 60) return 'warn'; if (p >= 85) return 'good';
if (p >= 77) return 'warn';
return 'bad'; return 'bad';
} }
@ -100,25 +102,43 @@ export function downloadText(filename: string, text: string, mime = 'application
setTimeout(() => URL.revokeObjectURL(url), 1000); setTimeout(() => URL.revokeObjectURL(url), 1000);
} }
/**
* Copies text to the clipboard. The async Clipboard API only exists on secure origins
* (HTTPS or localhost), so a self-hosted server opened over plain HTTP falls back to a hidden
* textarea and `execCommand('copy')`. That textarea is placed inside the open dialog, if any:
* dialogs trap focus, and a textarea outside the trap cannot be focused or selected, which
* made every copy button inside a dialog silently fail.
*/
export async function copyText(text: string): Promise<boolean> { export async function copyText(text: string): Promise<boolean> {
try { if (navigator.clipboard?.writeText && window.isSecureContext) {
await navigator.clipboard.writeText(text);
return true;
} catch {
try { try {
const ta = document.createElement('textarea'); await navigator.clipboard.writeText(text);
ta.value = text; return true;
ta.style.position = 'fixed';
ta.style.opacity = '0';
document.body.appendChild(ta);
ta.select();
const ok = document.execCommand('copy');
ta.remove();
return ok;
} catch { } catch {
return false; /* permission denied or document not focused: try the fallback */
} }
} }
const previous = document.activeElement as HTMLElement | null;
const host = (previous?.closest('[role="dialog"], [role="alertdialog"]') as HTMLElement | null) ?? document.querySelector<HTMLElement>('[role="dialog"][data-state="open"]') ?? document.body;
const ta = document.createElement('textarea');
ta.value = text;
ta.setAttribute('readonly', '');
ta.setAttribute('aria-hidden', 'true');
Object.assign(ta.style, { position: 'fixed', top: '0', left: '0', width: '1px', height: '1px', padding: '0', border: '0', opacity: '0', pointerEvents: 'none' });
host.appendChild(ta);
let ok = false;
try {
ta.focus({ preventScroll: true });
ta.select();
ta.setSelectionRange(0, text.length);
ok = document.execCommand('copy');
} catch {
ok = false;
} finally {
ta.remove();
previous?.focus?.({ preventScroll: true });
}
return ok;
} }
export function shuffle<T>(items: readonly T[]): T[] { export function shuffle<T>(items: readonly T[]): T[] {

View file

@ -1,5 +1,5 @@
import { useQuery, useQueryClient } from '@tanstack/react-query'; import { useQuery, useQueryClient } from '@tanstack/react-query';
import { MessageSquare, Trash2 } from 'lucide-react'; import { MessageSquare, Plus, Trash2 } from 'lucide-react';
import { useNavigate, useParams } from 'react-router'; import { useNavigate, useParams } from 'react-router';
import AssistantPanel from '@/features/AssistantPanel'; import AssistantPanel from '@/features/AssistantPanel';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
@ -12,7 +12,12 @@ export default function AssistantPage() {
const navigate = useNavigate(); const navigate = useNavigate();
const qc = useQueryClient(); const qc = useQueryClient();
const confirm = useConfirm(); const confirm = useConfirm();
const history = useQuery({ queryKey: ['ai', 'conversations'], queryFn: () => api.get<{ conversations: { id: string; title: string; updatedAt: number }[] }>('/api/ai/conversations').then((r) => r.conversations) }); const history = useQuery({
queryKey: ['ai', 'conversations'],
queryFn: () => api.get<{ conversations: { id: string; title: string; updatedAt: number; running?: boolean }[] }>('/api/ai/conversations').then((r) => r.conversations),
// Keep "Working…" labels current while an answer is being written in the background.
refetchInterval: (q) => (q.state.data?.some((c) => c.running) ? 3000 : false),
});
const remove = async (id: string) => { const remove = async (id: string) => {
if (!(await confirm({ title: 'Delete this conversation?', confirmLabel: 'Delete', danger: true, message: 'The messages are removed. Drafts and anything you saved are kept.' }))) return; if (!(await confirm({ title: 'Delete this conversation?', confirmLabel: 'Delete', danger: true, message: 'The messages are removed. Drafts and anything you saved are kept.' }))) return;
@ -22,9 +27,14 @@ export default function AssistantPage() {
}; };
return ( return (
<div className="-mx-4 -mt-6 -mb-28 flex h-[calc(100dvh-52px-56px)] sm:-mx-8 lg:mx-0 lg:-mt-10 lg:-mb-16 lg:h-dvh lg:gap-6"> <div className="flex h-[calc(100dvh-52px-56px)] lg:h-dvh">
<aside className="hidden w-60 shrink-0 flex-col border-r border-line py-6 pr-3 lg:flex"> <aside className="hidden w-64 shrink-0 flex-col border-r border-line bg-paper px-3 py-5 lg:flex">
<div className="eyebrow mb-2 px-2">Conversations</div> <div className="mb-2 flex items-center justify-between px-2">
<span className="eyebrow">Conversations</span>
<IconButton label="New chat" size="sm" className="-mr-1.5 size-7" onClick={() => navigate('/assistant')}>
<Plus />
</IconButton>
</div>
<div className="min-h-0 flex-1 space-y-0.5 overflow-y-auto"> <div className="min-h-0 flex-1 space-y-0.5 overflow-y-auto">
{(history.data ?? []).length === 0 && <p className="px-2 text-[13px] text-ink-3">Your conversations will be listed here.</p>} {(history.data ?? []).length === 0 && <p className="px-2 text-[13px] text-ink-3">Your conversations will be listed here.</p>}
{(history.data ?? []).map((c) => ( {(history.data ?? []).map((c) => (
@ -34,7 +44,7 @@ export default function AssistantPage() {
<MessageSquare className="size-3.5 shrink-0 text-ink-3" /> <MessageSquare className="size-3.5 shrink-0 text-ink-3" />
<span className="truncate text-sm">{c.title}</span> <span className="truncate text-sm">{c.title}</span>
</span> </span>
<span className="pl-[22px] text-[11px] text-ink-3">{timeAgo(c.updatedAt)}</span> <span className="pl-[22px] text-[11px] text-ink-3">{c.running ? 'Working…' : timeAgo(c.updatedAt)}</span>
</button> </button>
<IconButton label="Delete conversation" size="sm" className="mr-1 opacity-0 group-hover:opacity-100 focus-visible:opacity-100" onClick={() => remove(c.id)}> <IconButton label="Delete conversation" size="sm" className="mr-1 opacity-0 group-hover:opacity-100 focus-visible:opacity-100" onClick={() => remove(c.id)}>
<Trash2 /> <Trash2 />
@ -43,7 +53,7 @@ export default function AssistantPage() {
))} ))}
</div> </div>
</aside> </aside>
<div className="flex min-w-0 flex-1 flex-col"> <div className="flex min-w-0 flex-1 flex-col bg-surface/40">
<AssistantPanel variant="page" conversationId={conversationId} onConversationChange={(id) => navigate(id ? `/assistant/${id}` : '/assistant', { replace: true })} /> <AssistantPanel variant="page" conversationId={conversationId} onConversationChange={(id) => navigate(id ? `/assistant/${id}` : '/assistant', { replace: true })} />
</div> </div>
</div> </div>

View file

@ -43,6 +43,7 @@ import type { DeckItem, DocumentItem, Folder, Item, NoteItem, QuizItem } from '@
import { cx, downloadFile, formatBytes, gradeTone, plural, timeAgo, useDocumentTitle, useLocalStorage } from '@/lib/util'; import { cx, downloadFile, formatBytes, gradeTone, plural, timeAgo, useDocumentTitle, useLocalStorage } from '@/lib/util';
import { SortableList, type SortableRenderProps } from '@/ui/Sortable'; import { SortableList, type SortableRenderProps } from '@/ui/Sortable';
import { Badge, Button, Dialog, EmptyState, ErrorState, Field, IconButton, Input, Menu, MenuItem, MenuSeparator, ProgressBar, Segmented, Skeleton, Textarea, useConfirm } from '@/ui'; import { Badge, Button, Dialog, EmptyState, ErrorState, Field, IconButton, Input, Menu, MenuItem, MenuSeparator, ProgressBar, Segmented, Skeleton, Textarea, useConfirm } from '@/ui';
import { letterGrade } from '@shared/content';
type Filter = 'all' | 'quiz' | 'deck' | 'document' | 'note'; type Filter = 'all' | 'quiz' | 'deck' | 'document' | 'note';
@ -70,7 +71,7 @@ function itemMeta(item: Item): ReactNode {
<> <>
<span>{plural(q.questionCount, 'question')}</span> <span>{plural(q.questionCount, 'question')}</span>
{q.lastPercent !== null && ( {q.lastPercent !== null && (
<span className={cx('num font-medium', { good: 'text-good', warn: 'text-warn', bad: 'text-bad', none: '' }[gradeTone(q.lastPercent)])}>Last {q.lastPercent}%</span> <span className={cx('num font-medium', { good: 'text-good', warn: 'text-warn', bad: 'text-bad', none: '' }[gradeTone(q.lastPercent)])}>Last {letterGrade(q.lastPercent ?? 0)} · {q.lastPercent}%</span>
)} )}
{q.lastStudiedAt && <span>{timeAgo(q.lastStudiedAt)}</span>} {q.lastStudiedAt && <span>{timeAgo(q.lastStudiedAt)}</span>}
</> </>

View file

@ -343,7 +343,6 @@ export default function DeckPage() {
</div> </div>
<CardEditor value={fresh} onChange={setFresh} onSubmit={addCard} /> <CardEditor value={fresh} onChange={setFresh} onSubmit={addCard} />
<div className="mt-4 flex items-center justify-end gap-3"> <div className="mt-4 flex items-center justify-end gap-3">
<span className="hidden text-xs text-ink-3 sm:block">Ctrl+Enter adds the card and starts the next one</span>
<Button variant="primary" icon={<Plus />} loading={adding} disabled={!fresh.front.trim() || !fresh.back.trim()} onClick={addCard}> <Button variant="primary" icon={<Plus />} loading={adding} disabled={!fresh.front.trim() || !fresh.back.trim()} onClick={addCard}>
Add card Add card
</Button> </Button>

View file

@ -149,7 +149,7 @@ export default function DraftPage() {
</p> </p>
<ProgressBar value={Math.max(0.04, draft.progress)} className="mx-auto mt-6 h-2 max-w-sm" label="Generation progress" /> <ProgressBar value={Math.max(0.04, draft.progress)} className="mx-auto mt-6 h-2 max-w-sm" label="Generation progress" />
{draft.kind !== 'note' && partial > 0 && <p className="mt-3 text-sm text-ink-3">{plural(partial, draft.kind === 'quiz' ? 'question' : 'card')} so far</p>} {draft.kind !== 'note' && partial > 0 && <p className="mt-3 text-sm text-ink-3">{plural(partial, draft.kind === 'quiz' ? 'question' : 'card')} so far</p>}
<p className="mt-6 text-[13px] text-ink-3">You can leave this page. The draft keeps generating and will be waiting here.</p> <p className="mt-6 text-[13px] text-ink-3">You can leave this page. Generation continues on the server; follow it under Drafts in the sidebar (or on Today) and come back when it is ready.</p>
<Button <Button
variant="ghost" variant="ghost"
className="mt-4" className="mt-4"

View file

@ -9,6 +9,8 @@ import { useAiStatus, useClasses, useOverview } from '@/lib/queries';
import type { AttemptSummary } from '@/lib/types'; import type { AttemptSummary } from '@/lib/types';
import { cx, gradeTone, pct, plural, timeAgo, useDocumentTitle } from '@/lib/util'; import { cx, gradeTone, pct, plural, timeAgo, useDocumentTitle } from '@/lib/util';
import { Badge, Button, ClassDot, ErrorState, ProgressBar, Section, Skeleton } from '@/ui'; import { Badge, Button, ClassDot, ErrorState, ProgressBar, Section, Skeleton } from '@/ui';
import { DraftsSection } from '@/features/DraftsTray';
import { letterGrade } from '@shared/content';
function greeting(): string { function greeting(): string {
const h = new Date().getHours(); const h = new Date().getHours();
@ -186,6 +188,8 @@ export default function Home() {
</div> </div>
</div> </div>
<DraftsSection />
{o.activeAttempts.length > 0 && ( {o.activeAttempts.length > 0 && (
<Section title="Pick up where you left off"> <Section title="Pick up where you left off">
<div className="card divide-y divide-line overflow-hidden"> <div className="card divide-y divide-line overflow-hidden">
@ -247,7 +251,7 @@ export default function Home() {
const tone = gradeTone(p); const tone = gradeTone(p);
return ( return (
<Link key={a.id} to={`/session/${a.id}`} className="flex items-center gap-3 px-4 py-3 hover:bg-ink/4"> <Link key={a.id} to={`/session/${a.id}`} className="flex items-center gap-3 px-4 py-3 hover:bg-ink/4">
<span className={cx('num grid h-9 w-12 shrink-0 place-items-center rounded-[10px] text-sm font-semibold', tone === 'good' ? 'bg-good-soft text-good' : tone === 'warn' ? 'bg-warn-soft text-warn' : tone === 'bad' ? 'bg-bad-soft text-bad' : 'bg-sunken text-ink-3')}>{p === null ? '—' : `${p}%`}</span> <span className={cx('num grid h-9 min-w-12 shrink-0 place-items-center rounded-[10px] px-1.5 text-[13px] font-semibold', tone === 'good' ? 'bg-good-soft text-good' : tone === 'warn' ? 'bg-warn-soft text-warn' : tone === 'bad' ? 'bg-bad-soft text-bad' : 'bg-sunken text-ink-3')}>{p === null ? '—' : `${letterGrade(p)} ${p}%`}</span>
<span className="min-w-0 flex-1"> <span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium">{a.title}</span> <span className="block truncate text-sm font-medium">{a.title}</span>
<span className="text-xs text-ink-3"> <span className="text-xs text-ink-3">

View file

@ -10,6 +10,7 @@ import { useAiStatus, useClasses } from '@/lib/queries';
import type { Insights } from '@/lib/types'; import type { Insights } from '@/lib/types';
import { cx, gradeTone, pct, plural, timeAgo, useDocumentTitle } from '@/lib/util'; import { cx, gradeTone, pct, plural, timeAgo, useDocumentTitle } from '@/lib/util';
import { Button, ClassDot, EmptyState, ErrorState, PageHeader, Section, Segmented, Select, Skeleton } from '@/ui'; import { Button, ClassDot, EmptyState, ErrorState, PageHeader, Section, Segmented, Select, Skeleton } from '@/ui';
import { letterGrade } from '@shared/content';
function Stat({ label, value, sub, tone }: { label: string; value: string; sub?: string; tone?: 'good' | 'warn' | 'bad' | 'none' }) { function Stat({ label, value, sub, tone }: { label: string; value: string; sub?: string; tone?: 'good' | 'warn' | 'bad' | 'none' }) {
return ( return (
@ -184,7 +185,7 @@ export default function InsightsPage() {
const tone = gradeTone(p); const tone = gradeTone(p);
return ( return (
<Link key={a.id} to={`/session/${a.id}`} className="flex items-center gap-3 px-4 py-2.5 hover:bg-ink/4"> <Link key={a.id} to={`/session/${a.id}`} className="flex items-center gap-3 px-4 py-2.5 hover:bg-ink/4">
<span className={cx('num grid h-8 w-12 shrink-0 place-items-center rounded-[9px] text-[13px] font-semibold', tone === 'good' ? 'bg-good-soft text-good' : tone === 'warn' ? 'bg-warn-soft text-warn' : tone === 'bad' ? 'bg-bad-soft text-bad' : 'bg-sunken text-ink-3')}>{p === null ? '—' : `${p}%`}</span> <span className={cx('num grid h-8 min-w-12 shrink-0 place-items-center rounded-[9px] px-1.5 text-[12.5px] font-semibold', tone === 'good' ? 'bg-good-soft text-good' : tone === 'warn' ? 'bg-warn-soft text-warn' : tone === 'bad' ? 'bg-bad-soft text-bad' : 'bg-sunken text-ink-3')}>{p === null ? '—' : `${letterGrade(p)} ${p}%`}</span>
<span className="min-w-0 flex-1 truncate text-sm font-medium">{a.title}</span> <span className="min-w-0 flex-1 truncate text-sm font-medium">{a.title}</span>
<span className="shrink-0 text-xs text-ink-3"> <span className="shrink-0 text-xs text-ink-3">
{a.mode === 'exam' ? 'Exam · ' : ''} {a.mode === 'exam' ? 'Exam · ' : ''}

View file

@ -2,7 +2,7 @@ import { ArrowDown, ArrowUp, BookOpen, Check, ChevronRight, ClipboardList, Copy,
import { useEffect, useMemo, useRef, useState } from 'react'; import { useEffect, useMemo, useRef, useState } from 'react';
import { Link, useNavigate, useParams, useSearchParams } from 'react-router'; import { Link, useNavigate, useParams, useSearchParams } from 'react-router';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { blankQuestion, optionLetter, QUESTION_TYPE_LABEL, questionToDraft, validateDraftQuestion, type DraftCard, type DraftQuestion, type Question } from '@shared/content'; import { blankQuestion, letterGrade, optionLetter, QUESTION_TYPE_LABEL, questionToDraft, validateDraftQuestion, type DraftCard, type DraftQuestion, type Question } from '@shared/content';
import { parseImport } from '@shared/importer'; import { parseImport } from '@shared/importer';
import { MoveDialog, RenameDialog, ShareDialog } from '@/features/dialogs'; import { MoveDialog, RenameDialog, ShareDialog } from '@/features/dialogs';
import { QuestionEditor } from '@/features/editors'; import { QuestionEditor } from '@/features/editors';
@ -22,19 +22,20 @@ interface StartPrefs {
shuffleOptions: boolean; shuffleOptions: boolean;
} }
export function StartSessionDialog({ open, onClose, quizId, total, title }: { open: boolean; onClose: () => void; quizId: string; total: number; title: string }) { /** Session options (mode, length, shuffling, exam time limit), shared by the start screen and the start dialog. */
function useStartOptions(quizId: string, total: number, active: boolean) {
const { start, starting } = useStartSession(); const { start, starting } = useStartSession();
const [prefs, setPrefs] = useLocalStorage<StartPrefs>('sd.startPrefs', { mode: 'practice', shuffleQuestions: true, shuffleOptions: true }); const [prefs, setPrefs] = useLocalStorage<StartPrefs>('sd.startPrefs', { mode: 'practice', shuffleQuestions: true, shuffleOptions: true });
const [count, setCount] = useState(total); const [count, setCount] = useState(total);
const [timed, setTimed] = useState(false); const [timed, setTimed] = useState(false);
const [minutes, setMinutes] = useState(30); const [minutes, setMinutes] = useState(30);
useEffect(() => { useEffect(() => {
if (open) { if (active) {
setCount(total); setCount(total);
setMinutes(Math.max(5, Math.round(total * 1.2))); setMinutes(Math.max(5, Math.round(total * 1.2)));
setTimed(false); setTimed(false);
} }
}, [open, total]); }, [active, total]);
const go = () => const go = () =>
start({ start({
mode: prefs.mode, mode: prefs.mode,
@ -42,25 +43,15 @@ export function StartSessionDialog({ open, onClose, quizId, total, title }: { op
shuffleQuestions: prefs.shuffleQuestions, shuffleQuestions: prefs.shuffleQuestions,
shuffleOptions: prefs.shuffleOptions, shuffleOptions: prefs.shuffleOptions,
count: count < total ? count : undefined, count: count < total ? count : undefined,
// A time limit is an exam option only; practice sessions are never timed.
timeLimitMin: prefs.mode === 'exam' && timed ? minutes : null, timeLimitMin: prefs.mode === 'exam' && timed ? minutes : null,
}); });
return { prefs, setPrefs, count, setCount, timed, setTimed, minutes, setMinutes, go, starting, total };
}
function StartOptionsFields({ o }: { o: ReturnType<typeof useStartOptions> }) {
const { prefs, setPrefs, count, setCount, timed, setTimed, minutes, setMinutes, total } = o;
return ( return (
<Dialog
open={open}
onOpenChange={(o) => !o && onClose()}
title="Start a session"
description={title}
footer={
<>
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button variant="primary" icon={<Play className="fill-current" />} loading={starting} onClick={go}>
Start
</Button>
</>
}
>
<div className="space-y-5"> <div className="space-y-5">
<div className="grid grid-cols-2 gap-2" role="radiogroup" aria-label="Mode"> <div className="grid grid-cols-2 gap-2" role="radiogroup" aria-label="Mode">
{( {(
@ -102,10 +93,75 @@ export function StartSessionDialog({ open, onClose, quizId, total, title }: { op
)} )}
</div> </div>
</div> </div>
);
}
export function StartSessionDialog({ open, onClose, quizId, total, title }: { open: boolean; onClose: () => void; quizId: string; total: number; title: string }) {
const o = useStartOptions(quizId, total, open);
return (
<Dialog
open={open}
onOpenChange={(v) => !v && onClose()}
title="Start a session"
description={title}
footer={
<>
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button variant="primary" icon={<Play className="fill-current" />} loading={o.starting} onClick={o.go}>
Start
</Button>
</>
}
>
<StartOptionsFields o={o} />
</Dialog> </Dialog>
); );
} }
/** The quiz start screen: how to take it, without showing any questions or answers. */
function StartPanel({ quizId, total, resume, onShowQuestions }: { quizId: string; total: number; resume: { id: string; answeredCount: number; questionCount: number } | null; onShowQuestions: () => void }) {
const o = useStartOptions(quizId, total, true);
if (total === 0) {
return (
<div className="card border-dashed">
<EmptyState icon={<BookOpen />} title="No questions yet" action={<Button variant="primary" icon={<Plus />} onClick={onShowQuestions}>Add questions</Button>}>
Add questions to this quiz before taking it.
</EmptyState>
</div>
);
}
return (
<section className="card p-5 sm:p-6">
{resume && (
<Callout
tone="warn"
icon={<Play />}
className="mb-5"
title="You have a session in progress"
action={
<Button to={`/session/${resume.id}`} variant="marker" size="sm">
Resume ({resume.answeredCount}/{resume.questionCount})
</Button>
}
>
Pick up where you left off, or start a new session below.
</Callout>
)}
<StartOptionsFields o={o} />
<div className="mt-6 flex flex-wrap items-center gap-2 border-t border-line pt-5">
<Button variant="primary" size="lg" icon={<Play className="fill-current" />} loading={o.starting} onClick={o.go} className="min-w-40">
{resume ? 'Start new session' : 'Start'}
</Button>
<Button variant="ghost" size="lg" icon={<ClipboardList />} onClick={onShowQuestions} className="ml-auto">
View questions and answers
</Button>
</div>
</section>
);
}
/** Paste several questions (or cards) as text or JSON and add them to an existing item. */ /** Paste several questions (or cards) as text or JSON and add them to an existing item. */
export function BulkAddDialog({ open, onClose, kind, onAdd }: { open: boolean; onClose: () => void; kind: 'quiz' | 'deck'; onAdd: (items: unknown[]) => Promise<void> }) { export function BulkAddDialog({ open, onClose, kind, onAdd }: { open: boolean; onClose: () => void; kind: 'quiz' | 'deck'; onAdd: (items: unknown[]) => Promise<void> }) {
const [text, setText] = useState(''); const [text, setText] = useState('');
@ -230,7 +286,8 @@ export default function QuizPage() {
useAssistantContext(data?.quiz.classId, data?.quiz.title); useAssistantContext(data?.quiz.classId, data?.quiz.title);
const { start, starting } = useStartSession(); const { start, starting } = useStartSession();
const [tab, setTab] = useState<'questions' | 'history'>('questions'); // The start screen comes first, so opening a quiz never reveals its answers.
const [tab, setTab] = useState<'start' | 'questions' | 'history'>(() => (params.get('q') || params.get('edit') ? 'questions' : 'start'));
const [editing, setEditing] = useState<string | 'new' | null>(null); const [editing, setEditing] = useState<string | 'new' | null>(null);
const [draft, setDraft] = useState<DraftQuestion>(blankQuestion()); const [draft, setDraft] = useState<DraftQuestion>(blankQuestion());
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
@ -252,8 +309,10 @@ export default function QuizPage() {
if (params.get('edit')) { if (params.get('edit')) {
setDraft(blankQuestion()); setDraft(blankQuestion());
setEditing('new'); setEditing('new');
setTab('questions');
} }
const target = params.get('q'); const target = params.get('q');
if (target) setTab('questions');
if (target) setTimeout(() => document.getElementById(`q-${target}`)?.scrollIntoView({ block: 'center', behavior: 'smooth' }), 120); if (target) setTimeout(() => document.getElementById(`q-${target}`)?.scrollIntoView({ block: 'center', behavior: 'smooth' }), 120);
if (params.get('start') || params.get('edit')) { if (params.get('start') || params.get('edit')) {
next.delete('start'); next.delete('start');
@ -299,6 +358,7 @@ export default function QuizPage() {
setEditing(question.id); setEditing(question.id);
}; };
const beginNew = () => { const beginNew = () => {
setTab('questions');
setDraft({ ...blankQuestion(), topic: questions[questions.length - 1]?.topic ?? '' }); setDraft({ ...blankQuestion(), topic: questions[questions.length - 1]?.topic ?? '' });
setEditing('new'); setEditing('new');
setTimeout(() => newRef.current?.scrollIntoView({ block: 'center', behavior: 'smooth' }), 60); setTimeout(() => newRef.current?.scrollIntoView({ block: 'center', behavior: 'smooth' }), 60);
@ -358,7 +418,7 @@ export default function QuizPage() {
const editorFooter = (isNew: boolean) => ( const editorFooter = (isNew: boolean) => (
<div className="mt-5 flex flex-wrap items-center justify-end gap-2 border-t border-line pt-4"> <div className="mt-5 flex flex-wrap items-center justify-end gap-2 border-t border-line pt-4">
<span className="mr-auto hidden text-xs text-ink-3 sm:block">Ctrl+Enter to save</span> <span className="mr-auto" />
<Button variant="ghost" onClick={() => setEditing(null)}> <Button variant="ghost" onClick={() => setEditing(null)}>
Cancel Cancel
</Button> </Button>
@ -393,10 +453,16 @@ export default function QuizPage() {
{full.length > 0 && ( {full.length > 0 && (
<> <>
<span> <span>
Last <strong className="num text-ink">{last}%</strong> Last{' '}
<strong className="num text-ink">
{last !== null ? `${letterGrade(last)} · ${last}%` : '—'}
</strong>
</span> </span>
<span> <span>
Best <strong className="num text-ink">{best}%</strong> Best{' '}
<strong className="num text-ink">
{best !== null ? `${letterGrade(best)} · ${best}%` : '—'}
</strong>
</span> </span>
<span>{plural(history.length, 'attempt')}</span> <span>{plural(history.length, 'attempt')}</span>
</> </>
@ -414,9 +480,11 @@ export default function QuizPage() {
Resume ({data.activeAttempt.answeredCount}/{data.activeAttempt.questionCount}) Resume ({data.activeAttempt.answeredCount}/{data.activeAttempt.questionCount})
</Button> </Button>
) : null} ) : null}
<Button variant={data.activeAttempt ? 'secondary' : 'primary'} size="lg" icon={<Play className="fill-current" />} disabled={questions.length === 0} onClick={() => setStartOpen(true)}> {tab !== 'start' && (
{data.activeAttempt ? 'Start new' : 'Start'} <Button variant={data.activeAttempt ? 'secondary' : 'primary'} size="lg" icon={<Play className="fill-current" />} disabled={questions.length === 0} onClick={() => setStartOpen(true)}>
</Button> {data.activeAttempt ? 'Start new' : 'Start'}
</Button>
)}
<Menu <Menu
trigger={ trigger={
<IconButton label="Quiz options" tooltip={false}> <IconButton label="Quiz options" tooltip={false}>
@ -488,6 +556,7 @@ export default function QuizPage() {
onChange={setTab} onChange={setTab}
label="View" label="View"
options={[ options={[
{ value: 'start', label: 'Start', icon: <Play /> },
{ value: 'questions', label: `Questions`, icon: <ClipboardList /> }, { value: 'questions', label: `Questions`, icon: <ClipboardList /> },
{ value: 'history', label: `History${history.length ? ` (${history.length})` : ''}`, icon: <History /> }, { value: 'history', label: `History${history.length ? ` (${history.length})` : ''}`, icon: <History /> },
]} ]}
@ -509,7 +578,14 @@ export default function QuizPage() {
)} )}
</div> </div>
{tab === 'questions' ? ( {tab === 'start' ? (
<StartPanel
quizId={quiz.id}
total={questions.length}
resume={data.activeAttempt ? { id: data.activeAttempt.id, answeredCount: data.activeAttempt.answeredCount, questionCount: data.activeAttempt.questionCount } : null}
onShowQuestions={() => (questions.length === 0 ? beginNew() : setTab('questions'))}
/>
) : tab === 'questions' ? (
<> <>
{questions.length === 0 && editing !== 'new' ? ( {questions.length === 0 && editing !== 'new' ? (
<div className="card border-dashed"> <div className="card border-dashed">
@ -634,7 +710,7 @@ export default function QuizPage() {
<> <>
{full.length >= 2 && ( {full.length >= 2 && (
<Callout className="mb-3" tone={last !== null && best !== null && last >= best ? 'good' : 'neutral'}> <Callout className="mb-3" tone={last !== null && best !== null && last >= best ? 'good' : 'neutral'}>
{last !== null && best !== null && last >= best ? `Your latest attempt (${last}%) is your best so far.` : `Latest ${last}%, best ${best}% across ${plural(full.length, 'full attempt')}.`} {last !== null && best !== null && last >= best ? `Your latest attempt (${letterGrade(last)}, ${last}%) is your best so far.` : `Latest ${last !== null ? `${letterGrade(last)} (${last}%)` : '—'}, best ${best !== null ? `${letterGrade(best)} (${best}%)` : '—'} across ${plural(full.length, 'full attempt')}.`}
</Callout> </Callout>
)} )}
<ul className="card divide-y divide-line"> <ul className="card divide-y divide-line">
@ -644,7 +720,16 @@ export default function QuizPage() {
return ( return (
<li key={h.id}> <li key={h.id}>
<Link to={`/session/${h.id}`} className="flex items-center gap-3 px-4 py-3 hover:bg-ink/4"> <Link to={`/session/${h.id}`} className="flex items-center gap-3 px-4 py-3 hover:bg-ink/4">
<span className={cx('num grid h-10 w-14 shrink-0 place-items-center rounded-[10px] text-[15px] font-semibold', tone === 'good' ? 'bg-good-soft text-good' : tone === 'warn' ? 'bg-warn-soft text-warn' : tone === 'bad' ? 'bg-bad-soft text-bad' : 'bg-sunken text-ink-3')}>{p === null ? '—' : `${p}%`}</span> <span className={cx('num grid h-11 w-14 shrink-0 place-items-center rounded-[10px] leading-none font-semibold', tone === 'good' ? 'bg-good-soft text-good' : tone === 'warn' ? 'bg-warn-soft text-warn' : tone === 'bad' ? 'bg-bad-soft text-bad' : 'bg-sunken text-ink-3')}>
{p === null ? (
'—'
) : (
<span className="flex flex-col items-center gap-0.5">
<span className="text-[16px]">{letterGrade(p)}</span>
<span className="text-[11px] font-medium opacity-80">{p}%</span>
</span>
)}
</span>
<span className="min-w-0 flex-1"> <span className="min-w-0 flex-1">
<span className="block text-sm font-medium"> <span className="block text-sm font-medium">
{h.completedAt ? formatDateTime(h.completedAt) : ''} {h.completedAt ? formatDateTime(h.completedAt) : ''}

View file

@ -5,12 +5,12 @@ import { useNavigate, useSearchParams } from 'react-router';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { CardEditor } from '@/features/editors'; import { CardEditor } from '@/features/editors';
import { Explain } from '@/features/Explain'; import { Explain } from '@/features/Explain';
import { FlipCard, KeyHints, StreakChip, StudyFooter, StudyTopBar, useStreak } from '@/features/flashcards'; import { FlipCard, StreakChip, StudyFooter, StudyTopBar, useStreak } from '@/features/flashcards';
import { api, errorMessage } from '@/lib/api'; import { api, errorMessage } from '@/lib/api';
import { useAiStatus, useRefresh } from '@/lib/queries'; import { useAiStatus, useRefresh } from '@/lib/queries';
import type { DueCounts, QueueCard } from '@/lib/types'; import type { DueCounts, QueueCard } from '@/lib/types';
import { cx, formatMinutes, plural, useDocumentTitle, useHotkeys } from '@/lib/util'; import { cx, formatMinutes, plural, useDocumentTitle, useHotkeys } from '@/lib/util';
import { Badge, Button, ClassDot, Dialog, ErrorState, IconButton, Kbd, Menu, MenuItem, PageLoading } from '@/ui'; import { Badge, Button, ClassDot, Dialog, ErrorState, IconButton, Menu, MenuItem, PageLoading } from '@/ui';
interface QueueResponse { interface QueueResponse {
cards: QueueCard[]; cards: QueueCard[];
@ -207,7 +207,7 @@ export default function ReviewPage() {
<Badge tone="good">{counts.review} due</Badge> <Badge tone="good">{counts.review} due</Badge>
</div> </div>
<span className="num text-[13px] font-medium text-ink-2 sm:hidden">{remaining} left</span> <span className="num text-[13px] font-medium text-ink-2 sm:hidden">{remaining} left</span>
<IconButton label="Undo last rating (U)" onClick={undo} disabled={!last || busy}> <IconButton label="Undo last rating" onClick={undo} disabled={!last || busy}>
<Undo2 /> <Undo2 />
</IconButton> </IconButton>
{current && ( {current && (
@ -220,7 +220,6 @@ export default function ReviewPage() {
> >
<MenuItem <MenuItem
icon={<Pencil />} icon={<Pencil />}
hint="E"
onSelect={() => { onSelect={() => {
setDraft({ front: current.card.front, back: current.card.back, hint: current.card.hint, tags: current.card.tags }); setDraft({ front: current.card.front, back: current.card.back, hint: current.card.hint, tags: current.card.tags });
setEditing(current); setEditing(current);
@ -305,16 +304,6 @@ export default function ReviewPage() {
Show answer Show answer
</Button> </Button>
)} )}
<KeyHints
items={[
[<><Kbd>Space</Kbd><Kbd>↑</Kbd><Kbd>↓</Kbd></>, 'flip'],
[<Kbd>←</Kbd>, 'again'],
[<Kbd>→</Kbd>, 'good'],
[<><Kbd>1</Kbd>–<Kbd>4</Kbd></>, 'rate'],
[<Kbd>U</Kbd>, 'undo'],
[<Kbd>E</Kbd>, 'edit'],
]}
/>
</StudyFooter> </StudyFooter>
)} )}

View file

@ -4,6 +4,7 @@ import { lazy, Suspense, useEffect, useRef, useState, type ReactNode } from 'rea
import { NavLink, useNavigate, useParams } from 'react-router'; import { NavLink, useNavigate, useParams } from 'react-router';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { shareUrl } from '@/features/dialogs'; import { shareUrl } from '@/features/dialogs';
import { TemplateSettings } from '@/features/TemplateSettings';
import { api, errorMessage } from '@/lib/api'; import { api, errorMessage } from '@/lib/api';
import { qk, useRefresh } from '@/lib/queries'; import { qk, useRefresh } from '@/lib/queries';
import type { AppSettings, ShareListItem, Template } from '@/lib/types'; import type { AppSettings, ShareListItem, Template } from '@/lib/types';
@ -220,58 +221,6 @@ function SharingSettings() {
); );
} }
/* ------------------------------ templates ------------------------------ */
function TemplateSettings() {
const refresh = useRefresh();
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 }[] = [
{ kind: 'generation', title: 'AI generation presets', blurb: 'Appear under "Preset" when you generate with AI.' },
{ kind: 'quiz', title: 'Quiz templates', blurb: 'Appear under "Start from" when you create a quiz. Save any quiz as a template from its menu.' },
{ kind: 'deck', title: 'Flashcard templates', blurb: 'Appear under "Start from" when you create a deck.' },
];
return (
<>
{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.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.builtin && (
<IconButton
label="Delete template"
size="sm"
onClick={async () => {
await api.del(`/api/templates/${t.id}`).catch((e) => toast.error(errorMessage(e)));
await refresh();
}}
>
<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 text-xs text-ink-3">{g.blurb}</p>
</Section>
);
})}
</>
);
}
/* ------------------------------ data ------------------------------ */ /* ------------------------------ data ------------------------------ */
interface V1Summary { interface V1Summary {

View file

@ -362,11 +362,11 @@ function SharedNote({ note, back }: { note: PublicNote; back?: { to: string; lab
); );
} }
function SharedDocument({ doc, token }: { doc: PublicDocument; token: string }) { function SharedDocument({ doc, token, nested, back }: { doc: PublicDocument; token: string; nested?: boolean; back?: { to: string; label: string } }) {
const url = `/api/public/${token}/file`; const url = nested ? `/api/public/${token}/items/document/${doc.id}/file` : `/api/public/${token}/file`;
const inline = doc.docKind === 'pdf' || doc.docKind === 'image'; const inline = doc.docKind === 'pdf' || doc.docKind === 'image';
return ( return (
<Frame> <Frame back={back}>
<div className="eyebrow mb-2 flex items-center gap-1.5"> <div className="eyebrow mb-2 flex items-center gap-1.5">
<FileText className="size-3.5" /> Shared document <FileText className="size-3.5" /> Shared document
</div> </div>
@ -384,7 +384,7 @@ function SharedDocument({ doc, token }: { doc: PublicDocument; token: string })
); );
} }
const ITEM_ICON = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen /> }; const ITEM_ICON = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen />, document: <FileText /> };
function SharedCollection({ data, token }: { data: PublicCollection; token: string }) { function SharedCollection({ data, token }: { data: PublicCollection; token: string }) {
const groups = [{ id: null as string | null, name: '' }, ...data.folders].map((f) => ({ ...f, items: data.items.filter((i) => (f.id === null ? !i.folderId || !data.folders.some((x) => x.id === i.folderId) : i.folderId === f.id)) })).filter((g) => g.items.length > 0); const groups = [{ id: null as string | null, name: '' }, ...data.folders].map((f) => ({ ...f, items: data.items.filter((i) => (f.id === null ? !i.folderId || !data.folders.some((x) => x.id === i.folderId) : i.folderId === f.id)) })).filter((g) => g.items.length > 0);
@ -405,10 +405,10 @@ function SharedCollection({ data, token }: { data: PublicCollection; token: stri
{g.items.map((i) => ( {g.items.map((i) => (
<li key={`${i.kind}:${i.id}`}> <li key={`${i.kind}:${i.id}`}>
<Link to={`/s/${token}/${i.kind}/${i.id}`} className="flex items-center gap-3 px-4 py-3.5 hover:bg-ink/4"> <Link to={`/s/${token}/${i.kind}/${i.id}`} className="flex items-center gap-3 px-4 py-3.5 hover:bg-ink/4">
<span className={cx('grid size-10 shrink-0 place-items-center rounded-[11px] [&>svg]:size-[18px]', i.kind === 'quiz' ? 'bg-accent-soft text-accent' : i.kind === 'deck' ? 'bg-marker/45 text-ink dark:bg-marker/20 dark:text-marker' : 'bg-good-soft text-good')}>{ITEM_ICON[i.kind]}</span> <span className={cx('grid size-10 shrink-0 place-items-center rounded-[11px] [&>svg]:size-[18px]', i.kind === 'quiz' ? 'bg-accent-soft text-accent' : i.kind === 'deck' ? 'bg-marker/45 text-ink dark:bg-marker/20 dark:text-marker' : i.kind === 'document' ? 'bg-sunken text-ink-2' : 'bg-good-soft text-good')}>{ITEM_ICON[i.kind]}</span>
<span className="min-w-0 flex-1"> <span className="min-w-0 flex-1">
<span className="block truncate text-[15px] font-medium">{i.title}</span> <span className="block truncate text-[15px] font-medium">{i.title}</span>
<span className="text-xs text-ink-3">{i.kind === 'quiz' ? plural(i.count, 'question') : i.kind === 'deck' ? plural(i.count, 'card') : 'Note'}</span> <span className="text-xs text-ink-3">{i.kind === 'quiz' ? plural(i.count, 'question') : i.kind === 'deck' ? plural(i.count, 'card') : i.kind === 'document' ? `Document${i.count ? ` · ${plural(i.count, 'page')}` : ''}` : 'Note'}</span>
</span> </span>
<ChevronRight className="size-4 text-ink-3" /> <ChevronRight className="size-4 text-ink-3" />
</Link> </Link>
@ -464,7 +464,7 @@ export default function SharedPage() {
case 'note': case 'note':
return <SharedNote note={data} back={back} />; return <SharedNote note={data} back={back} />;
case 'document': case 'document':
return <SharedDocument doc={data} token={token} />; return <SharedDocument doc={data} token={token} nested={nested} back={back} />;
case 'collection': case 'collection':
return <SharedCollection data={data} token={token} />; return <SharedCollection data={data} token={token} />;
} }

View file

@ -580,10 +580,20 @@
@utility tab-slate { @utility tab-slate {
--tab: var(--c-slate); --tab: var(--c-slate);
} }
/* For bars with no bottom padding of their own (fixed-height footers and nav). */
@utility safe-bottom { @utility safe-bottom {
padding-bottom: max(env(safe-area-inset-bottom), 0px); padding-bottom: max(env(safe-area-inset-bottom), 0px);
} }
/*
* Bottom padding of 0.75rem plus the home-indicator inset. Use this instead of combining
* `safe-bottom` with `pb-3`/`py-3`: safe-bottom replaces the padding (to 0 on desktop),
* which left dialog footer buttons sitting on the bottom edge.
*/
@utility safe-pb-3 {
padding-bottom: calc(0.75rem + env(safe-area-inset-bottom, 0px));
}
@media print { @media print {
.no-print { .no-print {
display: none !important; display: none !important;

View file

@ -372,7 +372,7 @@ export function Dialog({
</RDialog.Close> </RDialog.Close>
</div> </div>
<div className={cx('min-h-0 flex-1 overflow-y-auto', !bare && 'px-5 pb-5 sm:px-6')}>{children}</div> <div className={cx('min-h-0 flex-1 overflow-y-auto', !bare && 'px-5 pb-5 sm:px-6')}>{children}</div>
{footer && <div className="safe-bottom flex flex-wrap items-center justify-end gap-2 border-t border-line bg-paper/60 px-5 py-3 sm:rounded-b-[18px] sm:px-6">{footer}</div>} {footer && <div className="safe-pb-3 flex flex-wrap items-center justify-end gap-2 border-t border-line bg-paper/60 px-5 pt-3 sm:rounded-b-[18px] sm:px-6">{footer}</div>}
</RDialog.Content> </RDialog.Content>
</RDialog.Portal> </RDialog.Portal>
</RDialog.Root> </RDialog.Root>