Fourth revision: OpenRouter, live tool stages, Explain layout, share sections
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 29s

- Interactive blocks are encouraged by default; Explain gets a reduced library
  and never writes practice questions.
- Assistant tool steps breathe while running, show live stages from generation
  and the Python check, and read in the past tense when done.
- The assistant asks before searching the web when class materials do not
  cover a question; clarifying questions list every class's exams and never
  ask about format (always NCLEX).
- Explain opens beside the question from 900px wide, moving the question left
  while open and back on the next one.
- Generate dialog drops the practice set/exam switch (presets cover it) and the
  Generate buttons lose their icon.
- Python check notes are green when every check passed, applied fixes neutral.
- Share pages group by exam, then Quizzes, Flashcards, Notes, Class Materials,
  hiding empty groups; the class page uses the same order. "Documents" is now
  "Class Materials".
- OpenRouter provider replaces the Ollama type; migration 6 turns Ollama
  connections into OpenAI-compatible ones at /v1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-15 21:54:39 -07:00
parent c595e0ff2c
commit 25bc03ea75
45 changed files with 663 additions and 329 deletions

View file

@ -88,6 +88,8 @@ interface ToolRun {
sources?: WebSource[];
/** The turn ends after this step: the model waits for the user (ask_user). */
endTurn?: boolean;
/** The step's line once it is done, when the past tense of the label is not right ("Wrote 12 quiz questions"). */
label?: string;
}
interface ToolSpec {
@ -102,12 +104,35 @@ interface ToolEnv {
context: AssistantContext;
signal?: AbortSignal;
modelId?: string | null;
/** Shows what a long-running tool is doing right now ("Checking the questions with Python"). */
progress?: (stage: string) => void;
}
const obj = (properties: Record<string, unknown>, required: string[] = []) => ({ type: 'object', properties, required });
const S = { type: 'string' } as const;
const clip = (text: string, max: number) => (text.length > max ? `${text.slice(0, max)}…` : text);
/** "Searching documents for …" → "Searched documents for …", for a finished step's line. */
const PAST: [RegExp, string][] = [
[/^Looking at /, 'Looked at '],
[/^Listing /, 'Listed '],
[/^Searching /, 'Searched '],
[/^Reading /, 'Read '],
[/^Opening /, 'Opened '],
[/^Reviewing /, 'Reviewed '],
[/^Writing /, 'Wrote '],
[/^Preparing /, 'Prepared '],
[/^Improving /, 'Improved '],
[/^Setting up /, 'Set up '],
[/^Creating /, 'Created '],
[/^Running /, 'Ran '],
[/^Asking /, 'Asked '],
];
export function pastTense(label: string): string {
for (const [re, to] of PAST) if (re.test(label)) return label.replace(re, to);
return label;
}
/* ------------------------------ tools ------------------------------ */
function classIdOr(env: ToolEnv, given: unknown): string | undefined {
@ -135,7 +160,7 @@ function requireClass(env: ToolEnv, given: unknown): string {
}
async function runGenerate(env: ToolEnv, request: Record<string, unknown>): Promise<ToolRun> {
const { draftId, done } = startGeneration(env.app, { ...request, modelId: undefined } as never, { conversationId: env.conversationId, origin: 'assistant' });
const { draftId, done } = startGeneration(env.app, { ...request, modelId: undefined } as never, { conversationId: env.conversationId, origin: 'assistant', onProgress: env.progress });
const onAbort = () => cancelGeneration(draftId);
env.signal?.addEventListener('abort', onAbort, { once: true });
const draft = await done;
@ -152,6 +177,7 @@ async function runGenerate(env: ToolEnv, request: Record<string, unknown>): Prom
important: 'This is a DRAFT shown to the user as a preview card. It is not saved. Tell the user to review and save it; do not claim it was added to their library.',
},
summary: `${draft.itemCount} ${unit}`,
label: draft.kind === 'quiz' ? `Wrote ${draft.itemCount} quiz question${draft.itemCount === 1 ? '' : 's'}` : draft.kind === 'deck' ? `Wrote ${draft.itemCount} flashcard${draft.itemCount === 1 ? '' : 's'}` : 'Wrote a study guide',
ui: [{ type: 'draft', draftId, kind: draft.kind, title: draft.title, count: draft.itemCount, status: 'ready' }],
};
}
@ -586,7 +612,7 @@ const TOOLS: ToolSpec[] = [
},
label: () => 'Improving questions',
run: async (input, env) => {
const { draftId, done } = startImprove(env.app, { quizId: String(input.quiz_id), questionIds: Array.isArray(input.question_ids) ? input.question_ids : undefined, instructions: input.instructions || undefined }, { conversationId: env.conversationId });
const { draftId, done } = startImprove(env.app, { quizId: String(input.quiz_id), questionIds: Array.isArray(input.question_ids) ? input.question_ids : undefined, instructions: input.instructions || undefined }, { conversationId: env.conversationId, onProgress: env.progress });
const draft = await done;
if (draft.status !== 'ready') throw new AIError('server', draft.error || 'Could not improve the questions.');
return {
@ -721,7 +747,7 @@ const TOOLS: ToolSpec[] = [
def: {
name: 'ask_user',
description:
"Ask the user up to 4 short clarifying questions BEFORE doing the work, when a detail that changes the result is missing: which exam or materials to use, how many questions or cards, the difficulty or focus. They appear as a small inline form with your options; your turn ends and the answers arrive as the user's next message. Offer concrete options (the class's exams, its documents by title, sensible counts) with the usual choice first and in `defaults`. Do not ask what the user already said or what is clear from context, ask at most once per request, and do not write the answer in the same turn.",
"Ask the user up to 4 short clarifying questions BEFORE doing the work, when a detail that changes the result is missing: which exam it is for, which materials to use, how many questions or cards, the difficulty or focus. They appear as a small inline form with your options; your turn ends and the answers arrive as the user's next message. Offer concrete options with the usual choice first and in `defaults`: for the exam, every exam of the class by name (plus 'All exams' when that makes sense); for materials, that exam's documents by title (multi); for counts, sensible numbers. Never ask about question format, style or type: every quiz is NCLEX style (multiple choice with select-all-that-apply mixed in) automatically. Do not ask what the user already said or what is clear from context, ask at most once per request, and do not write the answer in the same turn.",
parameters: obj(
{
intro: { ...S, description: 'Optional: one short sentence shown above the questions.' },
@ -1018,18 +1044,30 @@ function loadHistory(db: DB, conversationId: string, budgetTokens: number): Chat
return out;
}
function systemPrompt(app: AppContext, context: AssistantContext): string {
function systemPrompt(app: AppContext, context: AssistantContext, opts: { web?: boolean } = {}): string {
const { db } = app;
const s = getAppSettings(db, app.config.timezone);
const today = new Intl.DateTimeFormat('en-US', { timeZone: s.timezone, dateStyle: 'full' }).format(new Date());
const classes = db.all<{ id: string; name: string; code: string }>('SELECT id, name, code FROM classes WHERE archived = 0 ORDER BY sort_order LIMIT 40');
const classes = db.all<{ id: string; name: string; code: string; group_label: string }>('SELECT id, name, code, group_label FROM classes WHERE archived = 0 ORDER BY sort_order LIMIT 40');
// Every class's exams, so the assistant can offer them even when no class is in view.
const examsOf = new Map<string, { id: string; name: string }[]>();
for (const f of db.all<{ id: string; name: string; class_id: string }>('SELECT id, name, class_id FROM folders ORDER BY sort_order, created_at')) {
const list = examsOf.get(f.class_id) ?? [];
if (list.length < 20) list.push(f);
examsOf.set(f.class_id, list);
}
const classLine = (c: (typeof classes)[number]) => {
const exams = examsOf.get(c.id) ?? [];
const label = (c.group_label || 'Exam').toLowerCase();
return `- ${c.name}${c.code ? ` (${c.code})` : ''} — id ${c.id}${exams.length ? `; ${label}s: ${exams.map((e) => `${e.name} (exam_id ${e.id})`).join(', ')}` : ''}`;
};
const lines = [
'You are the study assistant built into Study Desk, a personal study app used by a nursing student. You help them learn, and you can act on their library through tools.',
`Today is ${today}.`,
classes.length ? `Their classes:\n${classes.map((c) => `- ${c.name}${c.code ? ` (${c.code})` : ''} — id ${c.id}`).join('\n')}` : 'They have not created any classes yet. Offer to create one with the organize tool when it would help.',
classes.length ? `Their classes:\n${classes.map(classLine).join('\n')}` : 'They have not created any classes yet. Offer to create one with the organize tool when it would help.',
];
lines.push(
"Clarifying questions: when a request to generate a quiz, flashcards or a study guide leaves out something that changes the result (which exam or which materials when the class has several, how many questions or cards), call ask_user once with those questions and concrete options, then stop. Don't ask when the user already said it, when the page in view makes it clear, or when they asked you to just go ahead; then use sensible defaults and say which you used.",
"Clarifying questions: when a request to generate a quiz, flashcards or a study guide leaves out something that changes the result (which exam it is for when the class has several, which materials, how many questions or cards), call ask_user once with those questions and concrete options, then stop. The exam question lists the class's exams by name, from the class list above. Never ask about the question format or style: quizzes are always NCLEX style. Don't ask when the user already said it, when the page in view makes it clear, or when they asked you to just go ahead; then use sensible defaults and say which you used.",
);
if (context.classId) {
const cls = db.get<{ name: string; group_label: string }>('SELECT name, group_label FROM classes WHERE id = ?', context.classId);
@ -1070,7 +1108,11 @@ function systemPrompt(app: AppContext, context: AssistantContext): string {
lines.push(
`How to work:
- Use tools instead of guessing. To answer questions about their material, search or read the documents first and base the answer on what you find.
- Cite document passages inline with the ref id in square brackets right after the claim, exactly as given, e.g. [c42]. Only cite refs that a tool returned in this conversation. If the documents do not cover something, say so, then answer from general knowledge and label it as such.
- Cite document passages inline with the ref id in square brackets right after the claim, exactly as given, e.g. [c42]. Only cite refs that a tool returned in this conversation. ${
opts.web
? 'If the documents do not cover something, say so and ask whether to search the web (see Web search below) instead of answering from your own knowledge.'
: 'If the documents do not cover something, say so, then answer from general knowledge and label it as such.'
}
- You can browse everything: list_materials and search_library for quizzes, flashcards and notes; get_quiz, get_deck and read_note to open them; search_documents and read_document for uploaded files.
- When you mention a specific quiz, deck, note or document, link it with Markdown using the url the tool gave you, for example [Cardiac drug cards](/decks/abc123). Never invent a url.
- To create study material, call generate_quiz, generate_flashcards or write_study_guide. They read the source documents themselves, so pass ids and a topic rather than text. Do not search first unless you need to work out which documents are relevant.
@ -1078,7 +1120,9 @@ function systemPrompt(app: AppContext, context: AssistantContext): string {
- Deleting, moving and renaming require propose_changes and the user's confirmation. Never claim a change was made before a system note confirms it.
- For "what should I study" questions, call get_performance and give specific, prioritised advice.
- When a request is clear, act on it without asking for permission. Ask one short question only when a missing detail would change the result (for example which class, when it is ambiguous).
- In the app, uploaded documents are called "class materials": use that term with the user.
- Be concise and concrete. Use Markdown. Teach like a good clinical instructor: explain the why, connect to patient care, and prefer current standard practice.
- Make teaching replies interactive without being asked: a comparison becomes a Table block, a process becomes Steps, a calculation becomes a small calculator, and a concept ends with a self-check Question and follow-up suggestions (see "Interactive blocks in replies" below).
- Talk while you work, like a person would: before a tool call that does real work (generating, checking, searching several places), first say in one short sentence what you are about to do ("I'll write 20 questions from the lecture, then check them with Python."), then call the tool in the same reply. After each step, say briefly what happened before the next one.
- After a tool produces a draft or a session link, reply with one or two sentences; the card already shows the details.
- Never mention tool names, ids (draft, search, extract or session ids) or raw tool output to the user. The app already shows each step as it happens; just say what you did and what you found.
@ -1278,8 +1322,8 @@ export async function runAssistantTurn(
}));
const tools = resolved.model.capabilities.tools ? [...TOOLS, ...mcpSpecs] : [];
const system =
systemPrompt(app, context) +
mcpPromptNote(mcp) +
systemPrompt(app, context, { web: mcp.servers.some((s) => s.builtin === 'web') }) +
mcpPromptNote(mcp, { askBeforeWeb: tools.some((t) => t.def.name === 'ask_user') }) +
genUiPrompt() +
(tools.length === 0 ? '\n\nNote: the selected model cannot use tools, so you cannot read the library or create drafts in this conversation. Say so if the user asks for that, and suggest choosing a tool-capable model in Settings.' : '');
const window = resolved.model.contextWindow ?? 32_000;
@ -1323,11 +1367,18 @@ export async function runAssistantTurn(
emit({ type: 'tool', tool: { ...activity } });
let output: string;
let isError = false;
const progress = (stage: string) => {
if (activity.status !== 'running' || stage === activity.stage) return;
activity.stage = stage;
emit({ type: 'tool', tool: { ...activity } });
};
try {
if (!spec) throw badRequest(`Unknown tool "${call.name}"`);
const run = await spec.run(call.input, env);
const run = await spec.run(call.input, { ...env, progress });
output = typeof run.output === 'string' ? run.output : JSON.stringify(run.output);
activity.status = 'done';
activity.stage = undefined;
if (!binding) activity.label = run.label ?? pastTense(activity.label);
activity.summary = run.summary;
activity.sources = run.sources;
activity.output = clipOutput(output);
@ -1342,6 +1393,7 @@ export async function runAssistantTurn(
const message = err instanceof z.ZodError ? err.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ') : err instanceof Error ? err.message : 'Tool failed';
output = JSON.stringify({ error: message });
activity.status = 'error';
activity.stage = undefined;
activity.summary = clip(message, 160);
if (!(err instanceof Error && ('status' in err || err instanceof AIError || err instanceof z.ZodError))) app.log('error', `Assistant tool ${call.name} failed`, err);
}