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
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:
parent
ccdad9728b
commit
f0aabe4d5d
63 changed files with 3892 additions and 488 deletions
|
|
@ -1,7 +1,7 @@
|
|||
import { Hono, type Context } from 'hono';
|
||||
import { streamSSE } from 'hono/streaming';
|
||||
import { z } from 'zod';
|
||||
import { assistantRequestSchema, displayMessages, listConversations, resolveAction, runAssistantTurn, type AssistantEvent } from '../ai/assistant.ts';
|
||||
import { assistantRequestSchema, displayMessages, followTurn, isTurnRunning, listConversations, mentionables, resolveAction, startAssistantTurn, stopTurn, type AssistantEvent } from '../ai/assistant.ts';
|
||||
import {
|
||||
cancelGeneration,
|
||||
createDraft,
|
||||
|
|
@ -10,6 +10,9 @@ import {
|
|||
generateRequestSchema,
|
||||
getDraft,
|
||||
improveRequestSchema,
|
||||
instructionPatchSchema,
|
||||
listInstructions,
|
||||
saveInstruction,
|
||||
listDrafts,
|
||||
saveDraft,
|
||||
startGeneration,
|
||||
|
|
@ -39,7 +42,7 @@ import {
|
|||
} from '../ai/service.ts';
|
||||
import { embedTexts, embeddingSettingsSchema, getEmbeddingSettings, embeddingStatus, rebuildIndex, saveEmbeddingSettings, scheduleIndexing } from '../services/semantic.ts';
|
||||
import { AIError } from '../ai/types.ts';
|
||||
import { badRequest, idParam, notFound, readBody, type AppContext } from '../http.ts';
|
||||
import { badRequest, HttpError, idParam, notFound, readBody, type AppContext } from '../http.ts';
|
||||
|
||||
type Emit<T> = (event: T) => void;
|
||||
|
||||
|
|
@ -72,7 +75,7 @@ const contentDraftSchema = z.discriminatedUnion('kind', [
|
|||
questions: z
|
||||
.array(
|
||||
z.object({
|
||||
type: z.enum(['single', 'multi']),
|
||||
type: z.enum(['single', 'multi', 'numeric']),
|
||||
stem: z.string().max(20000),
|
||||
options: z.array(z.object({ text: z.string().max(4000), correct: z.boolean(), why: z.string().max(20000).optional() })).max(12),
|
||||
rationale: z.string().max(20000).optional().default(''),
|
||||
|
|
@ -103,6 +106,13 @@ export function aiRoutes(app: AppContext): Hono {
|
|||
/* ------------------------------ configuration ------------------------------ */
|
||||
|
||||
r.get('/ai/meta', (c) => c.json({ adapters: listAdapterMeta(), tasks: TASK_INFO, catalogUpdated: CATALOG_UPDATED }));
|
||||
|
||||
/** Instructions the built-in generator sends to the model (editable in Settings → Templates). */
|
||||
r.get('/ai/instructions', (c) => c.json({ instructions: listInstructions(db) }));
|
||||
r.put('/ai/instructions', async (c) => {
|
||||
saveInstruction(db, await readBody(c, instructionPatchSchema));
|
||||
return c.json({ instructions: listInstructions(db) });
|
||||
});
|
||||
r.get('/ai/status', (c) => c.json(aiStatus(app)));
|
||||
|
||||
r.get('/ai/providers', (c) => c.json({ providers: listProviders(app) }));
|
||||
|
|
@ -181,28 +191,63 @@ export function aiRoutes(app: AppContext): Hono {
|
|||
|
||||
/* ------------------------------ assistant ------------------------------ */
|
||||
|
||||
/** Streams a running turn's events (replayed from its start) until it ends or the client leaves. */
|
||||
const follow = (conversationId: string, emit: Emit<AssistantEvent>, signal: AbortSignal) =>
|
||||
new Promise<void>((resolve) => {
|
||||
let unsubscribe: (() => void) | null = null;
|
||||
const finish = () => {
|
||||
unsubscribe?.();
|
||||
resolve();
|
||||
};
|
||||
unsubscribe = followTurn(conversationId, (event) => {
|
||||
emit(event);
|
||||
if (event.type === 'done') queueMicrotask(finish);
|
||||
});
|
||||
if (!unsubscribe) {
|
||||
emit({ type: 'done', conversationId, title: '' });
|
||||
return resolve();
|
||||
}
|
||||
// Leaving the page only stops the stream; the turn keeps running on the server.
|
||||
signal.addEventListener('abort', finish, { once: true });
|
||||
});
|
||||
|
||||
r.post('/ai/chat', async (c) => {
|
||||
const body = await readBody(c, assistantRequestSchema);
|
||||
return sse<AssistantEvent>(c, async (emit, signal) => {
|
||||
let conversationId: string;
|
||||
try {
|
||||
await runAssistantTurn(app, body, emit, signal);
|
||||
({ conversationId } = startAssistantTurn(app, body));
|
||||
} catch (err) {
|
||||
// Failures before the turn starts (no model configured, bad input) still reach the client as an event.
|
||||
// Failures before the turn starts (no model configured, bad input, already running) still reach the client as an event.
|
||||
const ai = err instanceof AIError ? err : null;
|
||||
if (!ai) app.log('error', 'Assistant request failed', err);
|
||||
emit({ type: 'error', code: ai?.code ?? 'server', message: ai?.message ?? 'The assistant could not start.', detail: ai?.providerMessage });
|
||||
const http = err instanceof HttpError ? err : null;
|
||||
if (!ai && !http) app.log('error', 'Assistant request failed', err);
|
||||
emit({ type: 'error', code: ai?.code ?? http?.code ?? 'server', message: ai?.message ?? http?.message ?? 'The assistant could not start.', detail: ai?.providerMessage });
|
||||
emit({ type: 'done', conversationId: body.conversationId ?? '', title: '' });
|
||||
return;
|
||||
}
|
||||
await follow(conversationId, emit, signal);
|
||||
});
|
||||
});
|
||||
|
||||
r.get('/ai/conversations', (c) => c.json({ conversations: listConversations(db) }));
|
||||
/** Re-attaches to a turn that is still running (after leaving and coming back). */
|
||||
r.get('/ai/chat/:id/stream', (c) => {
|
||||
const id = idParam(c);
|
||||
return sse<AssistantEvent>(c, (emit, signal) => follow(id, emit, signal));
|
||||
});
|
||||
|
||||
r.post('/ai/chat/:id/stop', (c) => c.json({ stopped: stopTurn(idParam(c)) }));
|
||||
|
||||
/** Library items that can be tagged with @ in the assistant. */
|
||||
r.get('/ai/mentionables', (c) => c.json({ items: mentionables(db, { classId: c.req.query('classId') || null, q: c.req.query('q') ?? '' }) }));
|
||||
|
||||
r.get('/ai/conversations', (c) => c.json({ conversations: listConversations(db).map((x) => ({ ...x, running: isTurnRunning(x.id) })) }));
|
||||
|
||||
r.get('/ai/conversations/:id', (c) => {
|
||||
const id = idParam(c);
|
||||
const row = db.get<{ id: string; title: string; class_id: string | null }>('SELECT id, title, class_id FROM conversations WHERE id = ?', id);
|
||||
if (!row) throw notFound('Conversation');
|
||||
return c.json({ conversation: { id: row.id, title: row.title, classId: row.class_id }, messages: displayMessages(db, id) });
|
||||
return c.json({ conversation: { id: row.id, title: row.title, classId: row.class_id, running: isTurnRunning(id) }, messages: displayMessages(db, id) });
|
||||
});
|
||||
|
||||
r.delete('/ai/conversations/:id', (c) => {
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import { badRequest, HttpError, idParam, readBody, type AppContext } from '../ht
|
|||
import { appSettingsSchema, deleteSetting, getAppSettings, getSetting, setSetting } from '../settings.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 { 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 { 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,
|
||||
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 },
|
||||
builtin: LLM_INSTRUCTIONS,
|
||||
}),
|
||||
);
|
||||
|
||||
|
|
@ -258,6 +259,8 @@ export function dataRoutes(app: AppContext): Hono {
|
|||
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) => {
|
||||
deleteTemplate(db, idParam(c));
|
||||
return c.json({ ok: true });
|
||||
|
|
|
|||
|
|
@ -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 };
|
||||
}
|
||||
|
||||
/** 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) {
|
||||
const { db } = app;
|
||||
const byFolder = share.kind === 'folder';
|
||||
|
|
@ -171,10 +171,13 @@ function collectionItems(app: AppContext, share: ShareRow) {
|
|||
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 [
|
||||
...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 })),
|
||||
...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');
|
||||
if (kind === 'quiz') return c.json(publicQuiz(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));
|
||||
});
|
||||
|
||||
/** Download for an explicitly shared document. */
|
||||
r.get('/:token/file', (c) => {
|
||||
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);
|
||||
const sendDocument = (documentId: string) => {
|
||||
const doc = db.get<{ filename: string; mime: string; storage_name: string }>('SELECT filename, mime, storage_name FROM documents WHERE id = ?', documentId);
|
||||
if (!doc) throw gone();
|
||||
const file = path.join(app.config.uploadsDir, path.basename(doc.storage_name));
|
||||
if (!fs.existsSync(file)) throw gone();
|
||||
|
|
@ -254,6 +255,22 @@ export function publicRoutes(app: AppContext): Hono {
|
|||
'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;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue