Third revision: web search, MCP sign-in, exams, intelligent UI, clarifying questions
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m0s
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m0s
- Built-in Parallel web search (keyless; optional sign-in for higher limits and research) with its own settings page; OAuth sign-in (RFC 9728/8414/7591, PKCE, RFC 8707) for any MCP server, with token refresh and pre-registered client support - Friendly tool steps (icon, name, status; details on click) and ids stripped from results; per-chat tool switches; taller thinking box - Exams within classes: exam tabs, scoped lists, uploads, imports and Generate; exam-only material for generation; class setting for what the groups are called - Assistant can ask clarifying questions in an inline form before generating - OpenUI blocks (charts, questions, flashcards, inputs) in assistant, Explain and share chats - Explain beside the quiz on wide screens, grounded in the cited source pages - Quiz results: percentage ring coloured by score band, rainbow at 100 - Share links: assistant button like the owner's, hidden during quizzes; documents readable in the browser - Live draft and library updates over server-sent events Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
60cf2322f7
commit
c595e0ff2c
54 changed files with 4710 additions and 387 deletions
154
web/src/features/AskCard.tsx
Normal file
154
web/src/features/AskCard.tsx
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
import { Check, CircleHelp, CornerDownLeft } from 'lucide-react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import type { AskQuestion, UiItem } from '@/lib/types';
|
||||
import { cx } from '@/lib/util';
|
||||
import { Button, Input } from '@/ui';
|
||||
|
||||
type Answer = { picked: string[]; typed: string };
|
||||
|
||||
function initial(q: AskQuestion): Answer {
|
||||
if (q.input === 'choice') {
|
||||
const labels = new Set((q.options ?? []).map((o) => o.label));
|
||||
const picked = (q.defaults ?? []).filter((d) => labels.has(d));
|
||||
return { picked: q.multi ? picked : picked.slice(0, 1), typed: '' };
|
||||
}
|
||||
return { picked: [], typed: q.defaults?.[0] ?? '' };
|
||||
}
|
||||
|
||||
function answerText(q: AskQuestion, a: Answer): string {
|
||||
const parts = [...a.picked, ...(a.typed.trim() ? [a.typed.trim()] : [])];
|
||||
return parts.length ? parts.join(', ') : 'no preference';
|
||||
}
|
||||
|
||||
/**
|
||||
* Clarifying questions from the assistant, as a small inline form. The answers go back as the
|
||||
* user's next message. Once the conversation moves on, the card folds to a quiet summary.
|
||||
*/
|
||||
export function AskCard({ item, answerable, onSend }: { item: Extract<UiItem, { type: 'questions' }>; answerable: boolean; onSend: (text: string) => void }) {
|
||||
const [answers, setAnswers] = useState<Answer[]>(() => item.questions.map(initial));
|
||||
const [sent, setSent] = useState(false);
|
||||
const open = answerable && !sent;
|
||||
const ready = useMemo(() => answers.some((a) => a.picked.length > 0 || a.typed.trim()), [answers]);
|
||||
|
||||
const set = (i: number, next: Partial<Answer>) => setAnswers((all) => all.map((a, j) => (j === i ? { ...a, ...next } : a)));
|
||||
const toggle = (i: number, q: AskQuestion, label: string) => {
|
||||
const a = answers[i];
|
||||
if (q.multi) set(i, { picked: a.picked.includes(label) ? a.picked.filter((l) => l !== label) : [...a.picked, label] });
|
||||
// A single choice replaces a typed answer, and picking it again clears it.
|
||||
else set(i, { picked: a.picked[0] === label ? [] : [label], typed: '' });
|
||||
};
|
||||
const submit = () => {
|
||||
setSent(true);
|
||||
onSend(item.questions.map((q, i) => (item.questions.length === 1 ? answerText(q, answers[i]) : `${q.question} → ${answerText(q, answers[i])}`)).join('\n'));
|
||||
};
|
||||
const skip = () => {
|
||||
setSent(true);
|
||||
onSend('No preference — use your best judgment.');
|
||||
};
|
||||
|
||||
if (!open) {
|
||||
return (
|
||||
<div className="rounded-[14px] border border-line bg-surface/60 px-3.5 py-2.5 text-[13px] text-ink-3">
|
||||
<div className="flex items-center gap-1.5 font-medium text-ink-2">
|
||||
<CircleHelp className="size-3.5" /> {item.questions.length === 1 ? 'Asked you' : `Asked you ${item.questions.length} questions`}
|
||||
</div>
|
||||
<ul className="mt-1 space-y-0.5">
|
||||
{item.questions.map((q) => (
|
||||
<li key={q.id} className="truncate">
|
||||
{q.question}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<form
|
||||
className="tool-pop rounded-[16px] border border-accent/40 bg-surface p-3.5 shadow-1"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
submit();
|
||||
}}
|
||||
>
|
||||
<div className="flex items-start gap-2.5">
|
||||
<span className="grid size-8 shrink-0 place-items-center rounded-[10px] bg-accent-soft text-accent">
|
||||
<CircleHelp className="size-4" />
|
||||
</span>
|
||||
<div className="min-w-0 pt-1 text-sm font-semibold">{item.intro || (item.questions.length === 1 ? 'A quick question first' : 'A few quick questions first')}</div>
|
||||
</div>
|
||||
<div className="mt-3 space-y-4">
|
||||
{item.questions.map((q, i) => {
|
||||
const a = answers[i];
|
||||
const name = `ask-${item.id}-${q.id}`;
|
||||
return (
|
||||
<fieldset key={q.id} className="min-w-0">
|
||||
<legend className="mb-1.5 text-[13.5px] font-medium text-ink">
|
||||
{q.question}
|
||||
{q.multi && <span className="ml-1.5 text-xs font-normal text-ink-3">Choose any</span>}
|
||||
</legend>
|
||||
{q.input === 'choice' && q.options ? (
|
||||
<>
|
||||
<div role={q.multi ? 'group' : 'radiogroup'} aria-label={q.question} className="flex flex-wrap gap-1.5">
|
||||
{q.options.map((o) => {
|
||||
const on = a.picked.includes(o.label);
|
||||
return (
|
||||
<button
|
||||
key={o.label}
|
||||
type="button"
|
||||
role={q.multi ? 'checkbox' : 'radio'}
|
||||
aria-checked={on}
|
||||
title={o.description}
|
||||
onClick={() => toggle(i, q, o.label)}
|
||||
className={cx(
|
||||
'flex min-h-9 max-w-full items-center gap-1.5 rounded-full border px-3 py-1.5 text-left text-[13px] transition-colors',
|
||||
on ? 'border-accent bg-accent-soft font-medium text-ink' : 'border-line bg-surface text-ink-2 hover:border-ink-3 hover:text-ink',
|
||||
)}
|
||||
>
|
||||
{on && <Check className="size-3.5 shrink-0 text-accent" />}
|
||||
<span className="min-w-0">
|
||||
<span className="block truncate">{o.label}</span>
|
||||
{o.description && <span className="block truncate text-[11.5px] font-normal text-ink-3">{o.description}</span>}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<Input
|
||||
aria-label={`${q.question} (your own answer)`}
|
||||
value={a.typed}
|
||||
onChange={(e) => set(i, { typed: e.target.value, ...(q.multi || !e.target.value ? {} : { picked: [] }) })}
|
||||
placeholder={q.placeholder || 'Or type your own'}
|
||||
className="mt-2 h-9 text-[13px]"
|
||||
maxLength={300}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<Input
|
||||
id={name}
|
||||
aria-label={q.question}
|
||||
type={q.input === 'number' ? 'number' : 'text'}
|
||||
inputMode={q.input === 'number' ? 'numeric' : undefined}
|
||||
min={q.input === 'number' ? 1 : undefined}
|
||||
value={a.typed}
|
||||
onChange={(e) => set(i, { typed: e.target.value })}
|
||||
placeholder={q.placeholder}
|
||||
className={cx('h-9 text-[13px]', q.input === 'number' && 'max-w-32')}
|
||||
maxLength={300}
|
||||
/>
|
||||
)}
|
||||
</fieldset>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="mt-4 flex flex-wrap items-center gap-2">
|
||||
<Button type="submit" size="sm" variant="primary" disabled={!ready} icon={<CornerDownLeft />}>
|
||||
Send answers
|
||||
</Button>
|
||||
<Button type="button" size="sm" variant="ghost" onClick={skip}>
|
||||
Skip, you decide
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,14 +1,16 @@
|
|||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { ArrowUp, BookOpen, Brain, Check, ChevronDown, ChevronRight, CircleAlert, FileText, Folder, History, Layers, LoaderCircle, NotebookPen, Play, Plus, Search, Sparkles, Square, Trash2, X } from 'lucide-react';
|
||||
import { ArrowUp, BookOpen, Brain, Check, ChevronDown, ChevronRight, CircleAlert, FileText, Folder, Globe, History, Layers, NotebookPen, Play, Plug, Plus, Search, SlidersHorizontal, Sparkles, Square, Trash2, X } from 'lucide-react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
||||
import { Link, useNavigate } from 'react-router';
|
||||
import { toast } from 'sonner';
|
||||
import { api, errorMessage, streamEvents } from '@/lib/api';
|
||||
import { assistant, ITEM_DRAG_TYPE, useAssistantState } from '@/lib/assistantStore';
|
||||
import { useAiModels, useAiStatus, useClasses, useRefresh } from '@/lib/queries';
|
||||
import type { AssistantEvent, ChatMessage, Mentionable, MessagePart, TaggedItem, TagKind, ToolActivity, UiItem } from '@/lib/types';
|
||||
import { qk, useAiModels, useAiStatus, useClasses, useRefresh } from '@/lib/queries';
|
||||
import type { AssistantEvent, ChatMessage, ChatToolSource, Mentionable, MessagePart, TaggedItem, TagKind, ToolActivity, UiItem } from '@/lib/types';
|
||||
import { cx, plural, timeAgo, useDebounced, useLocalStorage } from '@/lib/util';
|
||||
import { citedSources, Markdown, type Citation } from '@/ui/Markdown';
|
||||
import { citedSources, GenUiContext, Markdown, type Citation } from '@/ui/Markdown';
|
||||
import { AskCard } from './AskCard';
|
||||
import { ToolSteps } from './ToolSteps';
|
||||
import { Badge, Button, Callout, IconButton, Input, Menu, MenuItem, MenuLabel, MenuSeparator, Popover, Spinner } from '@/ui';
|
||||
|
||||
|
||||
|
|
@ -61,18 +63,6 @@ const DRAFT_ICON = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen />
|
|||
|
||||
/* ------------------------------ message parts ------------------------------ */
|
||||
|
||||
function ToolLine({ tool }: { tool: ToolActivity }) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 text-[13px] text-ink-2">
|
||||
{tool.status === 'running' ? <LoaderCircle className="size-3.5 shrink-0 animate-spin text-accent" /> : tool.status === 'error' ? <CircleAlert className="size-3.5 shrink-0 text-bad" /> : <Check className="size-3.5 shrink-0 text-good" />}
|
||||
<span className="min-w-0 truncate">
|
||||
{tool.label}
|
||||
{tool.summary && <span className={cx('ml-1.5', tool.status === 'error' ? 'text-bad' : 'text-ink-3')}>· {tool.summary}</span>}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DraftCard({ item, onNavigate }: { item: Extract<UiItem, { type: 'draft' }>; onNavigate: () => void }) {
|
||||
const gone = item.status === 'discarded';
|
||||
const saved = item.status === 'saved';
|
||||
|
|
@ -165,7 +155,7 @@ function ReasoningBox({ text, live }: { text: string; live: boolean }) {
|
|||
const el = e.currentTarget;
|
||||
follow.current = el.scrollHeight - el.scrollTop - el.clientHeight < 24;
|
||||
}}
|
||||
className="mt-1.5 max-h-32 overflow-y-auto rounded-[10px] border border-line bg-sunken/60 px-3 py-2 text-[12.5px] leading-relaxed whitespace-pre-wrap text-ink-3"
|
||||
className="mt-1.5 max-h-48 overflow-y-auto rounded-[10px] border border-line bg-sunken/60 px-3 py-2 text-[12.5px] leading-relaxed whitespace-pre-wrap text-ink-3"
|
||||
>
|
||||
{shown}
|
||||
</div>
|
||||
|
|
@ -174,32 +164,7 @@ function ReasoningBox({ text, live }: { text: string; live: boolean }) {
|
|||
);
|
||||
}
|
||||
|
||||
/** Tool steps that ran back to back: running ones listed, finished ones folded into one line. */
|
||||
function ToolGroup({ tools }: { tools: ToolActivity[] }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const running = tools.filter((t) => t.status === 'running');
|
||||
const finished = tools.filter((t) => t.status !== 'running');
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
{finished.length > 0 && (
|
||||
<div>
|
||||
<button type="button" aria-expanded={open} onClick={() => setOpen(!open)} className="flex items-center gap-1 text-xs font-medium text-ink-3 hover:text-ink-2">
|
||||
<ChevronRight className={cx('size-3.5 transition-transform', open && 'rotate-90')} />
|
||||
{finished.length === 1 ? finished[0].label : `${finished.length} steps`}
|
||||
{finished.length === 1 && finished[0].summary ? <span className="ml-1 truncate font-normal">· {finished[0].summary}</span> : null}
|
||||
{finished.some((t) => t.status === 'error') && <CircleAlert className="size-3.5 text-bad" />}
|
||||
</button>
|
||||
{open && <div className="mt-1.5 space-y-1 border-l-2 border-line pl-3">{finished.map((t) => <ToolLine key={t.id} tool={t} />)}</div>}
|
||||
</div>
|
||||
)}
|
||||
{running.map((t) => (
|
||||
<ToolLine key={t.id} tool={t} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AssistantMessage({ message, onNavigate, onAction }: { message: ChatMessage; onNavigate: () => void; onAction: (actionId: string, status: string, result: string) => void }) {
|
||||
function AssistantMessage({ message, onNavigate, onAction, onSend, answerable = false }: { message: ChatMessage; onNavigate: () => void; onAction: (actionId: string, status: string, result: string) => void; onSend: (text: string) => void; answerable?: boolean }) {
|
||||
const navigate = useNavigate();
|
||||
const citations = useMemo<Citation[]>(() => message.ui.flatMap((u) => (u.type === 'sources' ? u.items : [])), [message.ui]);
|
||||
const cited = useMemo(() => citedSources(message.text, citations), [message.text, citations]);
|
||||
|
|
@ -218,7 +183,7 @@ function AssistantMessage({ message, onNavigate, onAction }: { message: ChatMess
|
|||
if (p.text.trim()) blocks.push({ kind: 'text', text: p.text });
|
||||
} else if (p.kind === 'tool') {
|
||||
const tool = message.tools.find((t) => t.id === p.id);
|
||||
if (!tool) continue;
|
||||
if (!tool || (tool.name === 'ask_user' && tool.status === 'done')) continue;
|
||||
const last = blocks[blocks.length - 1];
|
||||
if (last?.kind === 'tools') last.tools.push(tool);
|
||||
else blocks.push({ kind: 'tools', tools: [tool] });
|
||||
|
|
@ -228,7 +193,9 @@ function AssistantMessage({ message, onNavigate, onAction }: { message: ChatMess
|
|||
}
|
||||
}
|
||||
|
||||
const genUi = useMemo(() => ({ streaming: Boolean(message.pending), onSend }), [message.pending, onSend]);
|
||||
return (
|
||||
<GenUiContext.Provider value={genUi}>
|
||||
<div className="space-y-2.5">
|
||||
{message.reasoning && <ReasoningBox text={message.reasoning} live={Boolean(message.pending) && !message.text} />}
|
||||
{blocks.map((b, i) =>
|
||||
|
|
@ -237,11 +204,13 @@ function AssistantMessage({ message, onNavigate, onAction }: { message: ChatMess
|
|||
{b.text}
|
||||
</Markdown>
|
||||
) : b.kind === 'tools' ? (
|
||||
<ToolGroup key={i} tools={b.tools} />
|
||||
<ToolSteps key={i} tools={b.tools} />
|
||||
) : b.item.type === 'draft' ? (
|
||||
<DraftCard key={i} item={b.item} onNavigate={onNavigate} />
|
||||
) : b.item.type === 'action' ? (
|
||||
<ActionCard key={i} item={b.item} onResolved={(status, result) => onAction((b.item as Extract<UiItem, { type: 'action' }>).actionId, status, result)} />
|
||||
) : b.item.type === 'questions' ? (
|
||||
<AskCard key={b.item.id} item={b.item} answerable={answerable && !message.pending} onSend={onSend} />
|
||||
) : b.item.type === 'link' ? (
|
||||
<Link key={i} to={`/${ITEM_URL[b.item.kind]}/${b.item.id}`} onClick={onNavigate} className="flex items-center gap-3 rounded-[14px] border border-line bg-surface p-3 shadow-1 hover:border-ink-3">
|
||||
<span className="grid size-9 shrink-0 place-items-center rounded-[10px] bg-marker text-marker-ink">
|
||||
|
|
@ -274,6 +243,7 @@ function AssistantMessage({ message, onNavigate, onAction }: { message: ChatMess
|
|||
</Callout>
|
||||
)}
|
||||
</div>
|
||||
</GenUiContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -354,6 +324,63 @@ function useMentionables(classId: string | null, query: string, enabled: boolean
|
|||
return (q.data ?? []).filter((i) => !needle || i.title.toLowerCase().includes(needle) || (i.folderName ?? '').toLowerCase().includes(needle)).slice(0, 40);
|
||||
}
|
||||
|
||||
/* ------------------------------ per-chat tools ------------------------------ */
|
||||
|
||||
/** Switches for the web search and MCP servers in this conversation, beside the + button. */
|
||||
function ToolsPicker({ off, onChange }: { off: string[]; onChange: (off: string[]) => void }) {
|
||||
const sources = useQuery({ queryKey: ['ai', 'chat-tools'], queryFn: () => api.get<{ sources: ChatToolSource[] }>('/api/ai/chat-tools').then((r) => r.sources), staleTime: 60_000 });
|
||||
const list = sources.data ?? [];
|
||||
if (list.length === 0) return null;
|
||||
const offCount = list.filter((s) => off.includes(s.id)).length;
|
||||
return (
|
||||
<Popover
|
||||
align="end"
|
||||
className="w-72 p-2"
|
||||
trigger={
|
||||
<IconButton label="Tools for this chat" size="sm" className="relative mb-0.5" tooltip={false}>
|
||||
<SlidersHorizontal />
|
||||
{offCount > 0 && <span className="absolute top-1 right-1 size-1.5 rounded-full bg-warn" aria-hidden />}
|
||||
</IconButton>
|
||||
}
|
||||
>
|
||||
<div className="px-2 pt-1 pb-2">
|
||||
<div className="text-sm font-semibold">Tools in this chat</div>
|
||||
<div className="text-[12px] text-ink-3">Switch sources off for this conversation only.</div>
|
||||
</div>
|
||||
<div className="space-y-0.5">
|
||||
{list.map((s) => {
|
||||
const on = !off.includes(s.id);
|
||||
return (
|
||||
<button
|
||||
key={s.id}
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={on}
|
||||
onClick={() => onChange(on ? [...off, s.id] : off.filter((x) => x !== s.id))}
|
||||
className="flex w-full items-center gap-2.5 rounded-lg px-2 py-2 text-left hover:bg-ink/5"
|
||||
>
|
||||
<span className={cx('grid size-7 shrink-0 place-items-center rounded-md [&>svg]:size-3.5', on ? 'bg-accent-soft text-accent' : 'bg-sunken text-ink-3')}>{s.kind === 'web' ? <Globe /> : <Plug />}</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-sm">{s.name}</span>
|
||||
<span className="block text-[11px] text-ink-3">{s.kind === 'web' ? 'Search and read web pages' : 'MCP server'}</span>
|
||||
</span>
|
||||
<span className={cx('relative h-5 w-9 shrink-0 rounded-full transition-colors', on ? 'bg-accent' : 'bg-ink/20')}>
|
||||
<span className={cx('absolute top-0.5 size-4 rounded-full bg-white shadow-1 transition-transform', on ? 'translate-x-[18px]' : 'translate-x-0.5')} />
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="mt-1.5 border-t border-line px-2 pt-1.5 text-[11px] text-ink-3">
|
||||
Manage them in{' '}
|
||||
<Link to="/settings/web" className="font-medium text-accent hover:underline">
|
||||
Settings
|
||||
</Link>
|
||||
</div>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ panel ------------------------------ */
|
||||
|
||||
export default function AssistantPanel({
|
||||
|
|
@ -387,6 +414,8 @@ export default function AssistantPanel({
|
|||
const [pickerQuery, setPickerQuery] = useState('');
|
||||
const [dropping, setDropping] = useState(false);
|
||||
const [modelId, setModelId] = useLocalStorage('sd.assistant.model', '');
|
||||
/** Web search and MCP servers switched off in this conversation (saved with it). */
|
||||
const [toolsOff, setToolsOff] = useState<string[]>([]);
|
||||
/** 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);
|
||||
|
|
@ -452,6 +481,8 @@ export default function AssistantPanel({
|
|||
}
|
||||
}
|
||||
if (e.type === 'done') finished = true;
|
||||
// A draft card means the drafts list changed.
|
||||
if (e.type === 'ui' && e.item.type === 'draft') void qc.invalidateQueries({ queryKey: qk.drafts });
|
||||
applyEvent(pendingId, e);
|
||||
});
|
||||
} catch (e) {
|
||||
|
|
@ -486,8 +517,9 @@ export default function AssistantPanel({
|
|||
stream.current?.abort();
|
||||
setLoadingHistory(true);
|
||||
try {
|
||||
const res = await api.get<{ conversation: { id: string; running?: boolean }; messages: ChatMessage[] }>(`/api/ai/conversations/${id}`);
|
||||
const res = await api.get<{ conversation: { id: string; running?: boolean; toolsOff?: string[] }; messages: ChatMessage[] }>(`/api/ai/conversations/${id}`);
|
||||
setConversation(id);
|
||||
setToolsOff(res.conversation.toolsOff ?? []);
|
||||
stick.current = true;
|
||||
if (!res.conversation.running) {
|
||||
setMessages(res.messages);
|
||||
|
|
@ -534,6 +566,7 @@ export default function AssistantPanel({
|
|||
setMessages([]);
|
||||
setFocusDocs([]);
|
||||
setTags([]);
|
||||
setToolsOff([]);
|
||||
onConversationChange?.(null);
|
||||
setTimeout(() => inputRef.current?.focus(), 30);
|
||||
}, [onConversationChange, setConversation]);
|
||||
|
|
@ -570,8 +603,10 @@ export default function AssistantPanel({
|
|||
conversationId: convo,
|
||||
message,
|
||||
modelId: effectiveModelId || undefined,
|
||||
toolsOff,
|
||||
context: {
|
||||
classId: opts.classId !== undefined ? opts.classId : context.classId,
|
||||
folderId: opts.classId !== undefined && opts.classId !== context.classId ? null : (context.folderId ?? null),
|
||||
documentIds: opts.documentIds ?? activeDocs,
|
||||
items: sentTags.map((t) => ({ kind: t.kind, id: t.id })),
|
||||
},
|
||||
|
|
@ -581,8 +616,10 @@ export default function AssistantPanel({
|
|||
),
|
||||
);
|
||||
},
|
||||
[busy, tags, follow, effectiveModelId, context.classId, activeDocs],
|
||||
[busy, tags, follow, effectiveModelId, context.classId, context.folderId, activeDocs, toolsOff],
|
||||
);
|
||||
/** Buttons and suggestion chips inside a reply send their text as the next message. */
|
||||
const sendFromBlock = useCallback((text: string) => void send(text), [send]);
|
||||
|
||||
// Requests from elsewhere in the app ("Ask about this document", "New questions on these topics").
|
||||
useEffect(() => {
|
||||
|
|
@ -627,7 +664,7 @@ export default function AssistantPanel({
|
|||
return ['What should I study today?', 'Find the questions I frequently get wrong and create a new practice quiz covering those concepts', 'Explain the difference between left-sided and right-sided heart failure', 'Start a practice session with the questions I miss most'];
|
||||
}, [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')) : context.folderId && context.label ? context.label : 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));
|
||||
|
||||
|
|
@ -776,7 +813,7 @@ export default function AssistantPanel({
|
|||
</div>
|
||||
) : (
|
||||
<div className="mx-auto max-w-2xl space-y-6">
|
||||
{messages.map((m) =>
|
||||
{messages.map((m, mi) =>
|
||||
m.role === 'user' ? (
|
||||
<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">
|
||||
|
|
@ -791,7 +828,7 @@ export default function AssistantPanel({
|
|||
</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} onSend={sendFromBlock} answerable={mi === messages.length - 1 && !busy} />
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
|
|
@ -900,6 +937,7 @@ export default function AssistantPanel({
|
|||
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"
|
||||
/>
|
||||
<ToolsPicker off={toolsOff} onChange={setToolsOff} />
|
||||
<Popover
|
||||
open={pickerOpen}
|
||||
onOpenChange={(o) => {
|
||||
|
|
|
|||
|
|
@ -1,28 +1,58 @@
|
|||
import { CornerDownLeft, Sparkles, Square } from 'lucide-react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { CornerDownLeft, PanelRightClose, Sparkles, Square } from 'lucide-react';
|
||||
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { errorMessage, streamEvents } from '@/lib/api';
|
||||
import { Markdown } from '@/ui/Markdown';
|
||||
import { Button, Callout, Spinner } from '@/ui';
|
||||
import type { ToolActivity } from '@/lib/types';
|
||||
import { cx } from '@/lib/util';
|
||||
import { GenUiContext, Markdown } from '@/ui/Markdown';
|
||||
import { Button, Callout, IconButton, Spinner } from '@/ui';
|
||||
import { ToolSteps } from './ToolSteps';
|
||||
|
||||
type ExplainBody =
|
||||
| { kind: 'question'; stem: string; options: { text: string; correct: boolean }[]; selected?: string[]; rationale?: string }
|
||||
| { kind: 'question'; stem: string; options: { text: string; correct: boolean }[]; selected?: string[]; rationale?: string; quizId?: string }
|
||||
| { kind: 'card'; front: string; back: string }
|
||||
| { kind: 'text'; text: string }
|
||||
// On a share link the item is named by id; the server loads its content.
|
||||
| { kind: 'question'; quizId: string; questionId: string; selected?: string[] }
|
||||
| { kind: 'card'; deckId: string; cardId: string };
|
||||
|
||||
type Event = { type: 'text'; delta: string } | { type: 'error'; message: string } | { type: 'done' };
|
||||
type Event = { type: 'text'; delta: string } | { type: 'tool'; tool: ToolActivity } | { type: 'error'; message: string } | { type: 'done' };
|
||||
|
||||
interface Turn {
|
||||
ask?: string;
|
||||
text: string;
|
||||
tools: ToolActivity[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set by the quiz runner: on wide screens the explanation opens in the empty space to the right
|
||||
* of the question instead of below it.
|
||||
*/
|
||||
export const ExplainSideContext = createContext(false);
|
||||
|
||||
/** Width available beside a centred 48rem column, or 0 when there is not enough room. */
|
||||
function useSideRoom(enabled: boolean): number {
|
||||
const measure = () => (typeof window === 'undefined' ? 0 : Math.floor((window.innerWidth - 768) / 2 - 44));
|
||||
const [room, setRoom] = useState(measure);
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
const onResize = () => setRoom(measure());
|
||||
window.addEventListener('resize', onResize);
|
||||
return () => window.removeEventListener('resize', onResize);
|
||||
}, [enabled]);
|
||||
return enabled && room >= 300 ? Math.min(room, 520) : 0;
|
||||
}
|
||||
|
||||
/** "Explain with AI": streams a short explanation and accepts follow-up questions. */
|
||||
export function Explain({ body, label = 'Explain with AI', className, url = '/api/ai/explain' }: { body: ExplainBody; label?: string; className?: string; url?: string }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [turns, setTurns] = useState<{ ask?: string; text: string }[]>([]);
|
||||
const [turns, setTurns] = useState<Turn[]>([]);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [ask, setAsk] = useState('');
|
||||
const abort = useRef<AbortController | null>(null);
|
||||
const key = JSON.stringify(body);
|
||||
const sideWidth = useSideRoom(useContext(ExplainSideContext));
|
||||
|
||||
useEffect(() => {
|
||||
// A different question: start over.
|
||||
|
|
@ -34,80 +64,114 @@ export function Explain({ body, label = 'Explain with AI', className, url = '/ap
|
|||
}, [key]);
|
||||
useEffect(() => () => abort.current?.abort(), []);
|
||||
|
||||
const run = async (question?: string) => {
|
||||
setOpen(true);
|
||||
setBusy(true);
|
||||
setError('');
|
||||
setTurns((t) => [...t, { ask: question, text: '' }]);
|
||||
const controller = new AbortController();
|
||||
abort.current = controller;
|
||||
try {
|
||||
await streamEvents<Event>(
|
||||
url,
|
||||
{ ...body, ask: question },
|
||||
(e) => {
|
||||
if (e.type === 'text') setTurns((t) => t.map((x, i) => (i === t.length - 1 ? { ...x, text: x.text + e.delta } : x)));
|
||||
else if (e.type === 'error') setError(e.message);
|
||||
},
|
||||
controller.signal,
|
||||
);
|
||||
} catch (e) {
|
||||
if ((e as Error)?.name !== 'AbortError') setError(errorMessage(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const run = useCallback(
|
||||
async (question?: string) => {
|
||||
setOpen(true);
|
||||
setBusy(true);
|
||||
setError('');
|
||||
setTurns((t) => [...t, { ask: question, text: '', tools: [] }]);
|
||||
const controller = new AbortController();
|
||||
abort.current = controller;
|
||||
const patchLast = (fn: (t: Turn) => Turn) => setTurns((t) => t.map((x, i) => (i === t.length - 1 ? fn(x) : x)));
|
||||
try {
|
||||
await streamEvents<Event>(
|
||||
url,
|
||||
{ ...body, ask: question },
|
||||
(e) => {
|
||||
if (e.type === 'text') patchLast((x) => ({ ...x, text: x.text + e.delta }));
|
||||
else if (e.type === 'tool') patchLast((x) => ({ ...x, tools: x.tools.some((t) => t.id === e.tool.id) ? x.tools.map((t) => (t.id === e.tool.id ? e.tool : t)) : [...x.tools, e.tool] }));
|
||||
else if (e.type === 'error') setError(e.message);
|
||||
},
|
||||
controller.signal,
|
||||
);
|
||||
} catch (e) {
|
||||
if ((e as Error)?.name !== 'AbortError') setError(errorMessage(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
},
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[key, url],
|
||||
);
|
||||
|
||||
const onSend = useCallback((text: string) => !busy && void run(text.slice(0, 500)), [busy, run]);
|
||||
const genUi = useMemo(() => ({ streaming: busy, onSend }), [busy, onSend]);
|
||||
|
||||
if (!open) {
|
||||
return (
|
||||
<Button size="sm" variant="ghost" icon={<Sparkles />} className={className} onClick={() => run()}>
|
||||
{label}
|
||||
<Button size="sm" variant="ghost" icon={<Sparkles />} className={className} onClick={() => (turns.length ? setOpen(true) : run())}>
|
||||
{turns.length ? 'Show the explanation' : label}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className={className}>
|
||||
<div className="rounded-xl border border-accent/25 bg-accent-soft/50 p-4">
|
||||
<div className="eyebrow mb-2 flex items-center gap-1.5 text-accent">
|
||||
<Sparkles className="size-3.5" /> AI explanation
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
|
||||
const panel: ReactNode = (
|
||||
<div className={cx('rounded-xl border border-accent/25 p-4', sideWidth > 0 ? 'flex max-h-full flex-col bg-surface shadow-2' : 'bg-accent-soft/50')}>
|
||||
<div className="eyebrow mb-2 flex shrink-0 items-center gap-1.5 text-accent">
|
||||
<Sparkles className="size-3.5" /> <span className="flex-1">AI explanation</span>
|
||||
{sideWidth > 0 && (
|
||||
<IconButton label="Close the explanation" size="sm" onClick={() => setOpen(false)} className="-my-1 text-ink-3">
|
||||
<PanelRightClose />
|
||||
</IconButton>
|
||||
)}
|
||||
</div>
|
||||
<GenUiContext.Provider value={genUi}>
|
||||
<div className={cx('space-y-3', sideWidth > 0 && 'min-h-0 flex-1 overflow-y-auto pr-1')}>
|
||||
{turns.map((t, i) => (
|
||||
<div key={i}>
|
||||
<div key={i} className="space-y-1.5">
|
||||
{t.ask && <div className="mb-1 text-[13px] font-medium text-ink-2">{t.ask}</div>}
|
||||
{t.text ? <Markdown className="text-[14.5px]">{t.text}</Markdown> : busy && i === turns.length - 1 ? <Spinner className="size-4" label="Thinking" /> : null}
|
||||
{t.tools.length > 0 && <ToolSteps tools={t.tools} compact />}
|
||||
{t.text ? <Markdown className="text-[14.5px]">{t.text}</Markdown> : busy && i === turns.length - 1 && !t.tools.some((x) => x.status === 'running') ? <Spinner className="size-4" label="Thinking" /> : null}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{error && (
|
||||
<Callout tone="bad" className="mt-3 py-2">
|
||||
{error}
|
||||
</Callout>
|
||||
)}
|
||||
<form
|
||||
className="mt-3 flex gap-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (busy) return abort.current?.abort();
|
||||
const question = ask.trim();
|
||||
if (!question) return;
|
||||
setAsk('');
|
||||
void run(question);
|
||||
}}
|
||||
>
|
||||
<input
|
||||
value={ask}
|
||||
onChange={(e) => setAsk(e.target.value)}
|
||||
placeholder="Ask a follow-up…"
|
||||
aria-label="Follow-up question"
|
||||
className="h-9 min-w-0 flex-1 rounded-[9px] border border-line-strong bg-surface px-3 text-sm outline-none focus:border-accent"
|
||||
/>
|
||||
<Button type="submit" size="sm" variant={busy ? 'secondary' : 'primary'} icon={busy ? <Square className="fill-current" /> : <CornerDownLeft />} aria-label={busy ? 'Stop' : 'Ask'}>
|
||||
{busy ? 'Stop' : 'Ask'}
|
||||
</Button>
|
||||
</form>
|
||||
<p className="mt-2 text-[11px] text-ink-3">AI can be wrong. Check anything important against your course material.</p>
|
||||
</div>
|
||||
</GenUiContext.Provider>
|
||||
{error && (
|
||||
<Callout tone="bad" className="mt-3 py-2">
|
||||
{error}
|
||||
</Callout>
|
||||
)}
|
||||
<form
|
||||
className="mt-3 flex shrink-0 gap-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (busy) return abort.current?.abort();
|
||||
const question = ask.trim();
|
||||
if (!question) return;
|
||||
setAsk('');
|
||||
void run(question);
|
||||
}}
|
||||
>
|
||||
<input
|
||||
value={ask}
|
||||
onChange={(e) => setAsk(e.target.value)}
|
||||
placeholder="Ask a follow-up…"
|
||||
aria-label="Follow-up question"
|
||||
className="h-9 min-w-0 flex-1 rounded-[9px] border border-line-strong bg-surface px-3 text-sm outline-none focus:border-accent"
|
||||
/>
|
||||
<Button type="submit" size="sm" variant={busy ? 'secondary' : 'primary'} icon={busy ? <Square className="fill-current" /> : <CornerDownLeft />} aria-label={busy ? 'Stop' : 'Ask'}>
|
||||
{busy ? 'Stop' : 'Ask'}
|
||||
</Button>
|
||||
</form>
|
||||
<p className="mt-2 shrink-0 text-[11px] text-ink-3">AI can be wrong. Check anything important against your course material.</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (sideWidth > 0) {
|
||||
// Wide screens: the explanation sits in the free space right of the question.
|
||||
return (
|
||||
<>
|
||||
<div className={cx('flex items-center gap-1.5 text-[13px] text-ink-3', className)}>
|
||||
<Sparkles className="size-3.5 text-accent" /> Explanation is open on the right
|
||||
</div>
|
||||
{createPortal(
|
||||
<aside aria-label="AI explanation" className="fixed top-[72px] bottom-[84px] z-30 flex animate-in flex-col" style={{ right: 20, width: sideWidth }}>
|
||||
{panel}
|
||||
</aside>,
|
||||
document.body,
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
return <div className={className}>{panel}</div>;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -46,8 +46,13 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
|
|||
const [templateId, setTemplateId] = useState('');
|
||||
const [verify, setVerify] = useLocalStorage('sd.generate.verify', true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
/** The exam (folder) this draft is for: its documents are the only ones offered, and the draft is saved there. */
|
||||
const [examId, setExamId] = useState<string | null>(folderId ?? null);
|
||||
const exams = cls.data?.folders ?? [];
|
||||
const groupLabel = cls.data?.class.groupLabel ?? 'Exam';
|
||||
|
||||
const docs = useMemo(() => (cls.data?.items.filter((i): i is DocumentItem => i.kind === 'document') ?? []).filter((d) => d.status === 'ready' && d.tokenCount > 0), [cls.data]);
|
||||
const allDocs = useMemo(() => (cls.data?.items.filter((i): i is DocumentItem => i.kind === 'document') ?? []).filter((d) => d.status === 'ready' && d.tokenCount > 0), [cls.data]);
|
||||
const docs = useMemo(() => (examId ? allDocs.filter((d) => d.folderId === examId) : allDocs), [allDocs, examId]);
|
||||
const fixedSource = Boolean(preset?.deckId || preset?.quizId || preset?.noteId);
|
||||
|
||||
useEffect(() => {
|
||||
|
|
@ -67,7 +72,15 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
|
|||
setSata(30);
|
||||
setCardStyle('concise');
|
||||
setNoteStyle('study_guide');
|
||||
}, [open, preset]);
|
||||
setExamId(folderId ?? null);
|
||||
}, [open, preset, folderId]);
|
||||
|
||||
// Inside an exam, start with all of its documents selected.
|
||||
useEffect(() => {
|
||||
if (!open || preset?.documentIds?.length || !cls.isSuccess) return;
|
||||
setDocIds(examId ? docs.map((d) => d.id) : []);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [open, examId, cls.isSuccess]);
|
||||
|
||||
// With no usable documents, default to describing a topic.
|
||||
useEffect(() => {
|
||||
|
|
@ -103,7 +116,7 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
|
|||
else if (mode === 'documents') source.documentIds = docIds;
|
||||
else if (mode === 'text') source.text = text;
|
||||
else if (mode === 'weak') source.weakAreas = true;
|
||||
const body: Record<string, unknown> = { kind, classId, folderId: folderId ?? null, source, focus: focus.trim() || undefined, instructions: instructions.trim() || undefined, modelId: modelId || undefined };
|
||||
const body: Record<string, unknown> = { kind, classId, folderId: examId, source, focus: focus.trim() || undefined, instructions: instructions.trim() || undefined, modelId: modelId || undefined };
|
||||
if (kind === 'quiz') Object.assign(body, { count, format, style: 'nclex', difficulty, sataShare: sata / 100, verify });
|
||||
else if (kind === 'deck') Object.assign(body, { count, cardStyle });
|
||||
else Object.assign(body, { noteStyle });
|
||||
|
|
@ -161,6 +174,19 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
|
|||
<div className="space-y-5">
|
||||
{!preset?.kind && <Segmented label="What to create" value={kind} onChange={(k) => (setKind(k), setCount(k === 'deck' ? 30 : 15), setTemplateId(''))} options={kinds} className="w-full" />}
|
||||
|
||||
{exams.length > 0 && (
|
||||
<Field label={groupLabel} hint={examId ? `Uses only this ${groupLabel.toLowerCase()}'s material, and the draft is saved in it.` : `Uses material from the whole class.`}>
|
||||
<Select value={examId ?? ''} onChange={(e) => setExamId(e.target.value || null)}>
|
||||
<option value="">Whole class</option>
|
||||
{exams.map((f) => (
|
||||
<option key={f.id} value={f.id}>
|
||||
{f.name}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</Field>
|
||||
)}
|
||||
|
||||
{fixedSource ? (
|
||||
<Callout icon={preset?.deckId ? <Layers /> : preset?.quizId ? <BookOpen /> : <NotebookPen />}>
|
||||
Source: <strong className="text-ink">{preset?.sourceLabel}</strong>
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { CircleAlert, CircleCheck, Plug, Plus, Trash2 } from 'lucide-react';
|
||||
import { CircleAlert, CircleCheck, LogIn, LogOut, Plug, Plus, ShieldCheck, Trash2 } from 'lucide-react';
|
||||
import { timeAgo } from '@/lib/util';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
|
|
@ -8,7 +9,7 @@ import { Badge, Button, Dialog, Field, Input, Section, Switch, Textarea, useConf
|
|||
type McpArea = 'chat' | 'explain' | 'generate' | 'check' | 'share';
|
||||
type McpAreas = Record<McpArea, boolean>;
|
||||
|
||||
const AREAS: { key: McpArea; label: string; description: string }[] = [
|
||||
export const AREAS: { key: McpArea; label: string; description: string }[] = [
|
||||
{ key: 'chat', label: 'Assistant chat', description: 'The sidebar and full-page assistant.' },
|
||||
{ key: 'explain', label: 'Explain this', description: 'Help on a quiz question, flashcard or passage.' },
|
||||
{ key: 'generate', label: 'Generating material', description: 'Writing quizzes, flashcards and study guides.' },
|
||||
|
|
@ -17,19 +18,30 @@ const AREAS: { key: McpArea; label: string; description: string }[] = [
|
|||
];
|
||||
const DEFAULT_AREAS: McpAreas = { chat: true, explain: true, generate: false, check: false, share: false };
|
||||
|
||||
interface McpServer {
|
||||
export interface McpServer {
|
||||
id: string;
|
||||
name: string;
|
||||
url: string;
|
||||
enabled: boolean;
|
||||
builtin: 'web' | null;
|
||||
instructions: string;
|
||||
areas: McpAreas;
|
||||
headerNames: string[];
|
||||
oauth: { connected: boolean; connectedAt: number | null; expiresAt: number | null; refreshable: boolean };
|
||||
clientId: string;
|
||||
hasClientSecret: boolean;
|
||||
options: { research: boolean };
|
||||
lastTestAt: number | null;
|
||||
lastTestOk: boolean | null;
|
||||
lastTestMessage: string | null;
|
||||
}
|
||||
|
||||
/** Sends the browser to the server's sign-in page; it comes back to `returnTo`. */
|
||||
export async function startMcpSignIn(id: string, returnTo: string): Promise<void> {
|
||||
const { url } = await api.post<{ url: string }>(`/api/ai/mcp/${id}/oauth/start`, { origin: window.location.origin, returnTo });
|
||||
window.location.href = url;
|
||||
}
|
||||
|
||||
interface TestResult {
|
||||
ok: boolean;
|
||||
message: string;
|
||||
|
|
@ -54,6 +66,8 @@ function ServerDialog({ open, existing, onClose, onSaved }: { open: boolean; exi
|
|||
const [headers, setHeaders] = useState('');
|
||||
const [instructions, setInstructions] = useState('');
|
||||
const [areas, setAreas] = useState<McpAreas>(DEFAULT_AREAS);
|
||||
const [clientId, setClientId] = useState('');
|
||||
const [clientSecret, setClientSecret] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
|
|
@ -63,13 +77,23 @@ function ServerDialog({ open, existing, onClose, onSaved }: { open: boolean; exi
|
|||
setHeaders('');
|
||||
setInstructions(existing?.instructions ?? '');
|
||||
setAreas({ ...DEFAULT_AREAS, ...existing?.areas });
|
||||
setClientId(existing?.clientId ?? '');
|
||||
setClientSecret('');
|
||||
}, [open, existing]);
|
||||
|
||||
const canSave = name.trim() && /^https?:\/\/\S+$/i.test(url.trim());
|
||||
const save = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const body = { name: name.trim(), url: url.trim(), instructions: instructions.trim(), areas, ...(headers.trim() ? { headers: parseHeaders(headers) } : existing ? {} : { headers: {} }) };
|
||||
const body = {
|
||||
name: name.trim(),
|
||||
url: url.trim(),
|
||||
instructions: instructions.trim(),
|
||||
areas,
|
||||
clientId: clientId.trim(),
|
||||
...(clientSecret.trim() ? { clientSecret: clientSecret.trim() } : {}),
|
||||
...(headers.trim() ? { headers: parseHeaders(headers) } : existing ? {} : { headers: {} }),
|
||||
};
|
||||
const res = existing ? await api.patch<{ server: McpServer }>(`/api/ai/mcp/${existing.id}`, body) : await api.post<{ server: McpServer }>('/api/ai/mcp', body);
|
||||
onSaved(res.server);
|
||||
onClose();
|
||||
|
|
@ -122,6 +146,18 @@ function ServerDialog({ open, existing, onClose, onSaved }: { open: boolean; exi
|
|||
<Field label="HTTP headers" optional hint={existing?.headerNames.length ? `Stored: ${existing.headerNames.join(', ')}. Entering anything here replaces them.` : 'One per line, as Name: value. Encrypted on the server and never shown again.'}>
|
||||
<Textarea rows={2} value={headers} onChange={(e) => setHeaders(e.target.value)} placeholder="Authorization: Bearer …" spellCheck={false} className="num text-[13px]" />
|
||||
</Field>
|
||||
<details className="rounded-xl border border-line px-3.5 py-2.5">
|
||||
<summary className="cursor-pointer text-sm font-medium text-ink">Sign-in app (advanced)</summary>
|
||||
<p className="mt-2 mb-3 text-xs text-ink-3">Most servers that need an account register this app automatically when you choose Sign in. Fill these in only if the server asks for a pre-registered OAuth app; use the redirect URL {window.location.origin}/api/ai/mcp/oauth/callback.</p>
|
||||
<div className="space-y-3">
|
||||
<Field label="Client ID" optional>
|
||||
<Input value={clientId} onChange={(e) => setClientId(e.target.value)} spellCheck={false} className="num text-[13px]" />
|
||||
</Field>
|
||||
<Field label="Client secret" optional hint={existing?.hasClientSecret ? 'Stored. Entering a new one replaces it.' : 'Encrypted on the server and never shown again.'}>
|
||||
<Input type="password" value={clientSecret} onChange={(e) => setClientSecret(e.target.value)} autoComplete="off" className="num text-[13px]" />
|
||||
</Field>
|
||||
</div>
|
||||
</details>
|
||||
<button type="submit" hidden />
|
||||
</form>
|
||||
</Dialog>
|
||||
|
|
@ -132,6 +168,20 @@ function ServerRow({ server, onEdit, reload }: { server: McpServer; onEdit: () =
|
|||
const confirm = useConfirm();
|
||||
const [testing, setTesting] = useState(false);
|
||||
const [tools, setTools] = useState<TestResult['tools'] | null>(null);
|
||||
const [signingIn, setSigningIn] = useState(false);
|
||||
const signIn = async () => {
|
||||
setSigningIn(true);
|
||||
await startMcpSignIn(server.id, '/settings/ai').catch((e) => toast.error(errorMessage(e)));
|
||||
setSigningIn(false);
|
||||
};
|
||||
const signOut = async () => {
|
||||
try {
|
||||
await api.del(`/api/ai/mcp/${server.id}/oauth`);
|
||||
reload();
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
}
|
||||
};
|
||||
|
||||
const test = async () => {
|
||||
setTesting(true);
|
||||
|
|
@ -182,6 +232,11 @@ function ServerRow({ server, onEdit, reload }: { server: McpServer; onEdit: () =
|
|||
{!AREAS.some((a) => server.areas[a.key]) && <span className="text-xs text-ink-3">Not used anywhere</span>}
|
||||
</div>
|
||||
{server.instructions && <p className="mt-1.5 line-clamp-2 text-xs text-ink-2">{server.instructions}</p>}
|
||||
{server.oauth.connected && (
|
||||
<div className="mt-1 flex items-center gap-1 text-xs text-good">
|
||||
<ShieldCheck className="size-3.5 shrink-0" /> Signed in{server.oauth.connectedAt ? ` ${timeAgo(server.oauth.connectedAt)}` : ''}
|
||||
</div>
|
||||
)}
|
||||
{server.lastTestAt && (
|
||||
<div className={`mt-1 flex items-center gap-1 text-xs ${server.lastTestOk ? 'text-good' : 'text-bad'}`}>
|
||||
{server.lastTestOk ? <CircleCheck className="size-3.5 shrink-0" /> : <CircleAlert className="size-3.5 shrink-0" />}
|
||||
|
|
@ -195,6 +250,15 @@ function ServerRow({ server, onEdit, reload }: { server: McpServer; onEdit: () =
|
|||
<Button size="sm" variant="secondary" loading={testing} onClick={test}>
|
||||
Test and list tools
|
||||
</Button>
|
||||
{server.oauth.connected ? (
|
||||
<Button size="sm" variant="ghost" icon={<LogOut />} onClick={signOut}>
|
||||
Sign out
|
||||
</Button>
|
||||
) : (
|
||||
<Button size="sm" variant="ghost" icon={<LogIn />} loading={signingIn} onClick={signIn}>
|
||||
Sign in
|
||||
</Button>
|
||||
)}
|
||||
<Button size="sm" variant="ghost" onClick={onEdit}>
|
||||
Edit
|
||||
</Button>
|
||||
|
|
@ -243,7 +307,7 @@ export function McpSettings() {
|
|||
) : (
|
||||
<div className="card p-4 text-sm text-ink-2">No MCP servers yet. Connect one to give the assistant extra tools, such as a drug reference or your own notes system.</div>
|
||||
)}
|
||||
<p className="mt-2.5 text-xs text-ink-3">Streamable HTTP servers only. Each server's tools are offered only in the places you allow, with your instructions on when to use them. Headers are encrypted and never sent back to the browser.</p>
|
||||
<p className="mt-2.5 text-xs text-ink-3">Streamable HTTP servers only. Each server's tools are offered only in the places you allow, with your instructions on when to use them. Servers that need an account: choose Sign in (OAuth). Headers and sign-in tokens are encrypted and never sent back to the browser. Web search has its own section.</p>
|
||||
<ServerDialog
|
||||
open={dialog.open}
|
||||
existing={dialog.existing}
|
||||
|
|
|
|||
|
|
@ -1,21 +1,25 @@
|
|||
import { CornerDownLeft, MessageCircleQuestion, Sparkles, Square, X } from 'lucide-react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { CornerDownLeft, Sparkles, Square, X } from 'lucide-react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { errorMessage, streamEvents } from '@/lib/api';
|
||||
import type { ToolActivity } from '@/lib/types';
|
||||
import { cx } from '@/lib/util';
|
||||
import { Markdown } from '@/ui/Markdown';
|
||||
import { Button, Callout, IconButton, Spinner } from '@/ui';
|
||||
import { GenUiContext, Markdown } from '@/ui/Markdown';
|
||||
import { Button, Callout, IconButton, Spinner, Tooltip } from '@/ui';
|
||||
import { ToolSteps } from './ToolSteps';
|
||||
|
||||
type Event = { type: 'text'; delta: string } | { type: 'error'; message: string } | { type: 'done' };
|
||||
type Event = { type: 'text'; delta: string } | { type: 'tool'; tool: ToolActivity } | { type: 'error'; message: string } | { type: 'done' };
|
||||
interface Turn {
|
||||
role: 'user' | 'assistant';
|
||||
text: string;
|
||||
tools?: ToolActivity[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The visitor-facing assistant on a share link (when the owner allows it). It answers from the
|
||||
* shared material only; the conversation lives in this tab and is never saved on the server.
|
||||
* `hidden` tucks it away (during a quiz or flashcard session) without losing the conversation.
|
||||
*/
|
||||
export function SharedAssistant({ token, title, item }: { token: string; title: string; item?: { kind: 'quiz' | 'deck' | 'note' | 'document'; id: string } }) {
|
||||
export function SharedAssistant({ token, title, item, hidden }: { token: string; title: string; item?: { kind: 'quiz' | 'deck' | 'note' | 'document'; id: string }; hidden?: boolean }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [turns, setTurns] = useState<Turn[]>([]);
|
||||
const [input, setInput] = useState('');
|
||||
|
|
@ -30,71 +34,90 @@ export function SharedAssistant({ token, title, item }: { token: string; title:
|
|||
if (el) el.scrollTop = el.scrollHeight;
|
||||
}, [turns, open]);
|
||||
|
||||
const send = async (text: string) => {
|
||||
// The server accepts the last 16 turns; older ones are dropped from the request.
|
||||
const history: Turn[] = [...turns, { role: 'user' as const, text }].slice(-15);
|
||||
setTurns([...turns, { role: 'user', text }, { role: 'assistant', text: '' }]);
|
||||
setBusy(true);
|
||||
setError('');
|
||||
const controller = new AbortController();
|
||||
abort.current = controller;
|
||||
try {
|
||||
await streamEvents<Event>(
|
||||
`/api/public/${token}/chat`,
|
||||
{ messages: history.filter((t) => t.text.trim()), item },
|
||||
(e) => {
|
||||
if (e.type === 'text') setTurns((t) => t.map((x, i) => (i === t.length - 1 ? { ...x, text: x.text + e.delta } : x)));
|
||||
else if (e.type === 'error') setError(e.message);
|
||||
},
|
||||
controller.signal,
|
||||
);
|
||||
} catch (e) {
|
||||
if ((e as Error)?.name !== 'AbortError') setError(errorMessage(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
// Drop an empty reply so the next request stays valid.
|
||||
setTurns((t) => (t[t.length - 1]?.role === 'assistant' && !t[t.length - 1].text ? t.slice(0, -1) : t));
|
||||
}
|
||||
};
|
||||
const send = useCallback(
|
||||
async (text: string) => {
|
||||
if (busy) return;
|
||||
// The server accepts the last 16 turns; older ones are dropped from the request.
|
||||
const history: Turn[] = [...turns, { role: 'user' as const, text }].slice(-15);
|
||||
setTurns([...turns, { role: 'user', text }, { role: 'assistant', text: '', tools: [] }]);
|
||||
setBusy(true);
|
||||
setError('');
|
||||
const controller = new AbortController();
|
||||
abort.current = controller;
|
||||
const patchLast = (fn: (t: Turn) => Turn) => setTurns((t) => t.map((x, i) => (i === t.length - 1 ? fn(x) : x)));
|
||||
try {
|
||||
await streamEvents<Event>(
|
||||
`/api/public/${token}/chat`,
|
||||
{ messages: history.filter((t) => t.text.trim()).map((t) => ({ role: t.role, text: t.text })), item },
|
||||
(e) => {
|
||||
if (e.type === 'text') patchLast((x) => ({ ...x, text: x.text + e.delta }));
|
||||
else if (e.type === 'tool') patchLast((x) => ({ ...x, tools: (x.tools ?? []).some((t) => t.id === e.tool.id) ? (x.tools ?? []).map((t) => (t.id === e.tool.id ? e.tool : t)) : [...(x.tools ?? []), e.tool] }));
|
||||
else if (e.type === 'error') setError(e.message);
|
||||
},
|
||||
controller.signal,
|
||||
);
|
||||
} catch (e) {
|
||||
if ((e as Error)?.name !== 'AbortError') setError(errorMessage(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
// Drop an empty reply so the next request stays valid.
|
||||
setTurns((t) => (t[t.length - 1]?.role === 'assistant' && !t[t.length - 1].text ? t.slice(0, -1) : t));
|
||||
}
|
||||
},
|
||||
[busy, turns, token, item],
|
||||
);
|
||||
const genUi = useMemo(() => ({ streaming: busy, onSend: (text: string) => void send(text.slice(0, 4000)) }), [busy, send]);
|
||||
|
||||
if (hidden) return null;
|
||||
if (!open) {
|
||||
// The same round sparkle button the owner sees in the app.
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(true)}
|
||||
className="fixed right-4 bottom-28 z-40 flex h-11 items-center gap-2 rounded-full bg-ink px-4 text-sm font-semibold text-paper shadow-2 hover:bg-ink/90 sm:right-6"
|
||||
>
|
||||
<MessageCircleQuestion className="size-[18px]" /> Ask about this
|
||||
</button>
|
||||
<Tooltip label="Ask the assistant" side="left">
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Open the assistant"
|
||||
onClick={() => setOpen(true)}
|
||||
className="fixed right-5 bottom-[max(1.25rem,env(safe-area-inset-bottom))] z-40 grid size-11 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"
|
||||
>
|
||||
<Sparkles className="size-[19px]" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<section aria-label="Study assistant" className="fixed right-4 bottom-4 z-40 flex h-[min(560px,calc(100dvh-2rem))] w-[min(420px,calc(100vw-2rem))] flex-col overflow-hidden rounded-[18px] border border-line bg-surface shadow-2 sm:right-6">
|
||||
<header className="flex items-center gap-2 border-b border-line px-4 py-2.5">
|
||||
<Sparkles className="size-4 text-accent" />
|
||||
<section aria-label="Study assistant" className="fixed right-4 bottom-4 z-40 flex h-[min(620px,calc(100dvh-2rem))] w-[min(440px,calc(100vw-2rem))] animate-in flex-col overflow-hidden rounded-[18px] border border-line bg-surface shadow-3 sm:right-6">
|
||||
<header className="flex items-center gap-2 border-b border-line px-3 py-2.5">
|
||||
<span className="grid size-8 shrink-0 place-items-center rounded-[10px] bg-ink text-marker">
|
||||
<Sparkles className="size-4" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-sm font-semibold">Ask about this</div>
|
||||
<div className="text-sm font-semibold">Assistant</div>
|
||||
<div className="truncate text-xs text-ink-3">{title}</div>
|
||||
</div>
|
||||
<IconButton label="Close" onClick={() => setOpen(false)}>
|
||||
<IconButton label="Close" size="sm" onClick={() => setOpen(false)}>
|
||||
<X />
|
||||
</IconButton>
|
||||
</header>
|
||||
<div ref={list} className="flex-1 space-y-3 overflow-y-auto px-4 py-3">
|
||||
<div ref={list} className="flex-1 space-y-4 overflow-y-auto px-4 py-3">
|
||||
{turns.length === 0 && <p className="text-[13.5px] text-ink-2">Ask a question about this material: what something means, why an answer is right, or for a quick recap.</p>}
|
||||
{turns.map((t, i) =>
|
||||
t.role === 'user' ? (
|
||||
<div key={i} className="ml-8 rounded-[14px] bg-accent-soft px-3 py-2 text-[14px] whitespace-pre-wrap">
|
||||
{t.text}
|
||||
</div>
|
||||
) : t.text ? (
|
||||
<Markdown key={i} className="text-[14px]">
|
||||
{t.text}
|
||||
</Markdown>
|
||||
) : busy && i === turns.length - 1 ? (
|
||||
<Spinner key={i} className="size-4" label="Thinking" />
|
||||
) : null,
|
||||
)}
|
||||
<GenUiContext.Provider value={genUi}>
|
||||
{turns.map((t, i) =>
|
||||
t.role === 'user' ? (
|
||||
<div key={i} className="flex justify-end">
|
||||
<div className="max-w-[88%] rounded-[16px] rounded-br-md bg-ink px-3.5 py-2 text-[14px] whitespace-pre-wrap text-paper">{t.text}</div>
|
||||
</div>
|
||||
) : (
|
||||
<div key={i} className="space-y-2">
|
||||
{t.tools && t.tools.length > 0 && <ToolSteps tools={t.tools} compact />}
|
||||
{t.text ? (
|
||||
<Markdown className="text-[14px]">{t.text}</Markdown>
|
||||
) : busy && i === turns.length - 1 && !t.tools?.some((x) => x.status === 'running') ? (
|
||||
<Spinner className="size-4" label="Thinking" />
|
||||
) : null}
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
</GenUiContext.Provider>
|
||||
{error && (
|
||||
<Callout tone="bad" className="py-2">
|
||||
{error}
|
||||
|
|
|
|||
199
web/src/features/ToolSteps.tsx
Normal file
199
web/src/features/ToolSteps.tsx
Normal file
|
|
@ -0,0 +1,199 @@
|
|||
/**
|
||||
* Tool steps in a conversation: one quiet line per step with a status mark (spinner, check or
|
||||
* cross) and a friendly name ("Searched the web for: sepsis bundle"). Clicking a line opens its
|
||||
* details: the pages it found, what it was asked and what it returned.
|
||||
*/
|
||||
import {
|
||||
BarChart3,
|
||||
BookMarked,
|
||||
BookOpenText,
|
||||
Check,
|
||||
ChevronRight,
|
||||
CircleHelp,
|
||||
FileSearch,
|
||||
FileText,
|
||||
Globe,
|
||||
Library,
|
||||
ListChecks,
|
||||
LoaderCircle,
|
||||
PencilLine,
|
||||
Play,
|
||||
Plug,
|
||||
Search,
|
||||
Sparkles,
|
||||
Telescope,
|
||||
Terminal,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import type { ToolActivity } from '@/lib/types';
|
||||
import { cx } from '@/lib/util';
|
||||
|
||||
const BUILTIN_ICON: Record<string, ReactNode> = {
|
||||
search_documents: <FileSearch />,
|
||||
read_document: <BookOpenText />,
|
||||
search_library: <Search />,
|
||||
list_materials: <Library />,
|
||||
list_classes: <Library />,
|
||||
get_quiz: <ListChecks />,
|
||||
get_deck: <ListChecks />,
|
||||
read_note: <BookOpenText />,
|
||||
get_performance: <BarChart3 />,
|
||||
generate_quiz: <Sparkles />,
|
||||
generate_flashcards: <Sparkles />,
|
||||
write_study_guide: <Sparkles />,
|
||||
improve_questions: <Sparkles />,
|
||||
create_draft: <PencilLine />,
|
||||
run_python: <Terminal />,
|
||||
start_practice: <Play />,
|
||||
propose_changes: <ListChecks />,
|
||||
organize: <Library />,
|
||||
read_sources: <BookMarked />,
|
||||
ask_user: <CircleHelp />,
|
||||
};
|
||||
|
||||
function iconFor(tool: ToolActivity): ReactNode {
|
||||
switch (tool.kind) {
|
||||
case 'web_search':
|
||||
return <Globe className={cx(tool.status === 'running' && 'tool-spin-slow')} />;
|
||||
case 'web_fetch':
|
||||
return <FileText />;
|
||||
case 'web_research':
|
||||
return <Telescope />;
|
||||
case 'mcp':
|
||||
return <Plug />;
|
||||
default:
|
||||
return BUILTIN_ICON[tool.name] ?? <Sparkles />;
|
||||
}
|
||||
}
|
||||
|
||||
/** The line's text: what is happening while it runs, what happened once it is done. */
|
||||
export function toolTitle(tool: ToolActivity): ReactNode {
|
||||
const subject = tool.subject ? <span className="text-ink-2">{tool.subject}</span> : null;
|
||||
if (tool.status === 'running') return tool.label;
|
||||
const failed = tool.status === 'error';
|
||||
switch (tool.kind) {
|
||||
case 'web_search':
|
||||
return failed ? 'Web search failed' : subject ? <>Searched the web for: {subject}</> : 'Searched the web';
|
||||
case 'web_fetch':
|
||||
return failed ? 'Could not read the page' : <>Read {subject ?? 'web pages'}</>;
|
||||
case 'web_research':
|
||||
return failed ? 'Web research failed' : subject ? <>Researched: {subject}</> : 'Researched on the web';
|
||||
case 'mcp':
|
||||
return failed ? `${tool.label} failed` : tool.label.replace(/^([^:]+): /, '$1 · ');
|
||||
default:
|
||||
return failed ? `${tool.label} (failed)` : tool.label;
|
||||
}
|
||||
}
|
||||
|
||||
function hostOf(url: string): string {
|
||||
try {
|
||||
return new URL(url).hostname.replace(/^www\./, '');
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
function Details({ tool }: { tool: ToolActivity }) {
|
||||
return (
|
||||
<div className="mt-1.5 mb-1 ml-[9px] space-y-2.5 border-l-2 border-line pt-0.5 pb-1 pl-4 text-[12.5px]">
|
||||
{tool.sources && tool.sources.length > 0 && (
|
||||
<ul className="space-y-1">
|
||||
{tool.sources.map((s) => (
|
||||
<li key={s.url}>
|
||||
<a href={s.url} target="_blank" rel="noreferrer noopener" className="group flex min-w-0 items-baseline gap-2 hover:text-ink">
|
||||
<span className="min-w-0 truncate font-medium text-ink group-hover:underline">{s.title}</span>
|
||||
<span className="shrink-0 text-[11.5px] text-ink-3">{hostOf(s.url)}</span>
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{tool.summary && <div className={cx(tool.status === 'error' ? 'text-bad' : 'text-ink-2')}>{tool.summary}</div>}
|
||||
{tool.server && <div className="text-ink-3">From the {tool.server} server</div>}
|
||||
{tool.input && tool.input !== '{}' && (
|
||||
<div>
|
||||
<div className="eyebrow mb-1">Request</div>
|
||||
<pre className="max-h-40 overflow-auto rounded-lg bg-sunken px-2.5 py-2 font-mono text-[11.5px] whitespace-pre-wrap text-ink-2">{tool.input}</pre>
|
||||
</div>
|
||||
)}
|
||||
{tool.output && (
|
||||
<div>
|
||||
<div className="eyebrow mb-1">Result</div>
|
||||
<pre className="max-h-48 overflow-auto rounded-lg bg-sunken px-2.5 py-2 font-mono text-[11.5px] whitespace-pre-wrap text-ink-2">{tool.output}</pre>
|
||||
</div>
|
||||
)}
|
||||
{!tool.sources?.length && !tool.summary && !tool.input && !tool.output && <div className="text-ink-3">{tool.status === 'running' ? 'Working…' : 'No details.'}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Mark({ tool }: { tool: ToolActivity }) {
|
||||
return (
|
||||
<span className="relative grid size-[18px] shrink-0 place-items-center text-ink-3 [&>svg]:size-[15px]">
|
||||
{iconFor(tool)}
|
||||
{tool.status === 'running' ? (
|
||||
<LoaderCircle className="absolute -inset-[3px] !size-[24px] animate-spin text-accent/70" strokeWidth={1.5} />
|
||||
) : (
|
||||
<span className={cx('tool-pop absolute -right-1 -bottom-1 grid size-[11px] place-items-center rounded-full ring-2 ring-paper', tool.status === 'error' ? 'bg-bad text-white' : 'bg-good text-white')}>
|
||||
{tool.status === 'error' ? <X className="!size-[8px]" strokeWidth={3.5} /> : <Check className="!size-[8px]" strokeWidth={3.5} />}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function ToolStep({ tool, compact }: { tool: ToolActivity; compact?: boolean }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<div className="min-w-0">
|
||||
<button type="button" aria-expanded={open} onClick={() => setOpen(!open)} className={cx('group flex max-w-full min-w-0 items-center gap-2.5 rounded-lg py-1 pr-2 text-left', compact ? 'text-[12.5px]' : 'text-[13.5px]')}>
|
||||
<Mark tool={tool} />
|
||||
<span className={cx('min-w-0 truncate', tool.status === 'running' ? 'tool-shimmer font-medium' : tool.status === 'error' ? 'text-bad' : 'text-ink-2 group-hover:text-ink')}>{toolTitle(tool)}</span>
|
||||
{tool.status === 'done' && tool.sources && tool.sources.length > 0 && <span className="num shrink-0 text-[11.5px] text-ink-3">{tool.sources.length} {tool.sources.length === 1 ? 'page' : 'pages'}</span>}
|
||||
<ChevronRight className={cx('size-3.5 shrink-0 text-ink-3 opacity-0 transition group-hover:opacity-100', open && 'rotate-90 opacity-100')} />
|
||||
</button>
|
||||
{open && <Details tool={tool} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Steps that ran back to back. More than three finished steps fold into one line. */
|
||||
export function ToolSteps({ tools, compact }: { tools: ToolActivity[]; compact?: boolean }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const running = tools.some((t) => t.status === 'running');
|
||||
if (tools.length <= 3 || running) {
|
||||
return (
|
||||
<div className="space-y-0.5">
|
||||
{tools.map((t) => (
|
||||
<ToolStep key={t.id} tool={t} compact={compact} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const failed = tools.filter((t) => t.status === 'error').length;
|
||||
return (
|
||||
<div>
|
||||
<button type="button" aria-expanded={open} onClick={() => setOpen(!open)} className={cx('group flex items-center gap-2.5 rounded-lg py-1 pr-2 text-left text-ink-2 hover:text-ink', compact ? 'text-[12.5px]' : 'text-[13.5px]')}>
|
||||
<span className="flex -space-x-1.5">
|
||||
{tools.slice(0, 3).map((t) => (
|
||||
<span key={t.id} className="grid size-[20px] place-items-center rounded-full bg-sunken text-ink-3 ring-2 ring-paper [&>svg]:size-[12px]">
|
||||
{iconFor({ ...t, status: 'done' })}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
<span>
|
||||
{tools.length} steps{failed ? <span className="text-bad"> · {failed} failed</span> : null}
|
||||
</span>
|
||||
<ChevronRight className={cx('size-3.5 text-ink-3 transition', open && 'rotate-90')} />
|
||||
</button>
|
||||
{open && (
|
||||
<div className="mt-0.5 space-y-0.5 pl-1">
|
||||
{tools.map((t) => (
|
||||
<ToolStep key={t.id} tool={t} compact={compact} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
159
web/src/features/WebSearchSettings.tsx
Normal file
159
web/src/features/WebSearchSettings.tsx
Normal file
|
|
@ -0,0 +1,159 @@
|
|||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { CircleAlert, CircleCheck, Globe, LogIn, LogOut, ShieldCheck } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
import { timeAgo } from '@/lib/util';
|
||||
import { Badge, Button, Callout, Field, Section, Switch, Textarea, useConfirm } from '@/ui';
|
||||
import { AREAS, startMcpSignIn, type McpServer } from './McpSettings';
|
||||
|
||||
const KEY = ['ai', 'web-search'];
|
||||
|
||||
/** The built-in web search (Parallel): on or off, where it is used, guidance, and an optional account. */
|
||||
export function WebSearchSettings() {
|
||||
const qc = useQueryClient();
|
||||
const confirm = useConfirm();
|
||||
const q = useQuery({ queryKey: KEY, queryFn: () => api.get<{ webSearch: McpServer }>('/api/ai/web-search').then((r) => r.webSearch) });
|
||||
const [instructions, setInstructions] = useState('');
|
||||
const [testing, setTesting] = useState(false);
|
||||
const [signingIn, setSigningIn] = useState(false);
|
||||
const [tools, setTools] = useState<string[] | null>(null);
|
||||
const ws = q.data;
|
||||
|
||||
useEffect(() => {
|
||||
if (ws) setInstructions(ws.instructions);
|
||||
}, [ws?.instructions]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const patch = async (body: Record<string, unknown>) => {
|
||||
try {
|
||||
const res = await api.patch<{ webSearch: McpServer }>('/api/ai/web-search', body);
|
||||
qc.setQueryData(KEY, res.webSearch);
|
||||
void qc.invalidateQueries({ queryKey: ['ai', 'chat-tools'] });
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
}
|
||||
};
|
||||
const test = async () => {
|
||||
setTesting(true);
|
||||
try {
|
||||
const res = await api.post<{ result: { ok: boolean; message: string; tools: { name: string }[] }; webSearch: McpServer }>('/api/ai/web-search/test');
|
||||
qc.setQueryData(KEY, res.webSearch);
|
||||
if (res.result.ok) {
|
||||
toast.success(res.result.message);
|
||||
setTools(res.result.tools.map((t) => t.name));
|
||||
} else toast.error(res.result.message);
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
} finally {
|
||||
setTesting(false);
|
||||
}
|
||||
};
|
||||
const signOut = async () => {
|
||||
if (!(await confirm({ title: 'Sign out of Parallel?', message: 'Web search keeps working on the free tier, with lower limits.', confirmLabel: 'Sign out' }))) return;
|
||||
try {
|
||||
await api.del(`/api/ai/mcp/${ws?.id}/oauth`);
|
||||
void qc.invalidateQueries({ queryKey: KEY });
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
}
|
||||
};
|
||||
|
||||
if (!ws) return null;
|
||||
const signedIn = ws.oauth.connected;
|
||||
return (
|
||||
<>
|
||||
<Section title="Web search">
|
||||
<div className="card p-4 sm:p-5">
|
||||
<div className="flex items-start gap-3.5">
|
||||
<span className="grid size-11 shrink-0 place-items-center rounded-[12px] bg-accent-soft text-accent">
|
||||
<Globe className="size-5" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<h3 className="text-[15px] font-semibold">Search the web</h3>
|
||||
{ws.enabled ? <Badge tone="good">On</Badge> : <Badge>Off</Badge>}
|
||||
</div>
|
||||
<p className="mt-0.5 text-[13.5px] text-ink-2">Lets the AI look up current guidelines, drug information and anything your own material doesn't cover, then cite the pages it used. Searches run through Parallel and work without an account.</p>
|
||||
</div>
|
||||
<Switch checked={ws.enabled} onChange={(v) => patch({ enabled: v })} label={<span className="sr-only">Use web search</span>} />
|
||||
</div>
|
||||
{ws.lastTestAt && (
|
||||
<div className={`mt-3 flex items-center gap-1.5 text-xs ${ws.lastTestOk ? 'text-good' : 'text-bad'}`}>
|
||||
{ws.lastTestOk ? <CircleCheck className="size-3.5 shrink-0" /> : <CircleAlert className="size-3.5 shrink-0" />}
|
||||
<span className="min-w-0 break-words">{ws.lastTestMessage}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-4 flex flex-wrap gap-2">
|
||||
<Button size="sm" variant="secondary" loading={testing} onClick={test}>
|
||||
Test the connection
|
||||
</Button>
|
||||
</div>
|
||||
{tools && <p className="mt-2 text-xs text-ink-3">Tools available: {tools.join(', ')}</p>}
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="Parallel account">
|
||||
<div className="card p-4 sm:p-5">
|
||||
{signedIn ? (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<ShieldCheck className="size-5 shrink-0 text-good" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-sm font-medium">Signed in</div>
|
||||
<div className="text-[13px] text-ink-3">Higher rate limits{ws.oauth.connectedAt ? ` · connected ${timeAgo(ws.oauth.connectedAt)}` : ''}. Usage counts against your Parallel account.</div>
|
||||
</div>
|
||||
<Button size="sm" variant="ghost" icon={<LogOut />} onClick={signOut}>
|
||||
Sign out
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-sm font-medium">Free tier, no account</div>
|
||||
<div className="text-[13px] text-ink-3">Sign in with a Parallel account for higher rate limits and in-depth research.</div>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="primary"
|
||||
icon={<LogIn />}
|
||||
loading={signingIn}
|
||||
onClick={async () => {
|
||||
setSigningIn(true);
|
||||
await startMcpSignIn(ws.id, '/settings/web').catch((e) => toast.error(errorMessage(e)));
|
||||
setSigningIn(false);
|
||||
}}
|
||||
>
|
||||
Sign in to Parallel
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-4 border-t border-line pt-4">
|
||||
<Switch
|
||||
checked={ws.options.research}
|
||||
disabled={!signedIn}
|
||||
onChange={(v) => patch({ research: v })}
|
||||
label="Allow in-depth research"
|
||||
description={signedIn ? 'The AI may run a slower research call for hard questions. Each one uses your Parallel credits.' : 'Needs a signed-in account.'}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="When and where to use it">
|
||||
<div className="card space-y-5 p-4 sm:p-5">
|
||||
<Field label="Your guidance for the AI" optional hint="For example: Only for current drug information and guidelines. Never for questions my course material answers.">
|
||||
<Textarea rows={3} value={instructions} maxLength={2000} onChange={(e) => setInstructions(e.target.value)} onBlur={() => instructions !== ws.instructions && patch({ instructions })} placeholder="Use the web for…" />
|
||||
</Field>
|
||||
<fieldset className="space-y-3">
|
||||
<legend className="mb-2 text-sm font-medium text-ink">Where it can be used</legend>
|
||||
{AREAS.map((a) => (
|
||||
<Switch key={a.key} checked={ws.areas[a.key]} onChange={(v) => patch({ areas: { [a.key]: v } })} label={a.label} description={a.key === 'share' ? 'Explain and Ask on links you share, when those are on. Searches run through your account if you are signed in.' : a.description} />
|
||||
))}
|
||||
</fieldset>
|
||||
</div>
|
||||
<Callout tone="neutral" className="mt-3 text-[13px]">
|
||||
Only the search words and page addresses the AI writes are sent to Parallel, never your documents. You can switch web search off for a single conversation from the assistant's tools button.
|
||||
</Callout>
|
||||
</Section>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -154,7 +154,7 @@ export function MoveDialog({ target, onClose }: { target: { kind: EditableKind;
|
|||
</Field>
|
||||
<Field label="Folder">
|
||||
<Select value={folderId} onChange={(e) => setFolderId(e.target.value)} disabled={detail.isLoading}>
|
||||
<option value="">No folder</option>
|
||||
<option value="">{`Not in a${/^[aeiou]/i.test(detail.data?.class.groupLabel ?? 'folder') ? 'n' : ''} ${(detail.data?.class.groupLabel ?? 'folder').toLowerCase()}`}</option>
|
||||
{(detail.data?.folders ?? []).map((f) => (
|
||||
<option key={f.id} value={f.id}>
|
||||
{f.name}
|
||||
|
|
@ -169,7 +169,7 @@ export function MoveDialog({ target, onClose }: { target: { kind: EditableKind;
|
|||
|
||||
/* ------------------------------ new item ------------------------------ */
|
||||
|
||||
export function NewItemDialog({ kind, classId, folderId, onClose }: { kind: 'quiz' | 'deck' | 'note' | 'folder' | null; classId: string; folderId?: string | null; onClose: () => void }) {
|
||||
export function NewItemDialog({ kind, classId, folderId, onClose, groupLabel = 'Folder' }: { kind: 'quiz' | 'deck' | 'note' | 'folder' | null; classId: string; folderId?: string | null; onClose: () => void; groupLabel?: string }) {
|
||||
const refresh = useRefresh();
|
||||
const navigate = useNavigate();
|
||||
const [title, setTitle] = useState('');
|
||||
|
|
@ -219,8 +219,8 @@ export function NewItemDialog({ kind, classId, folderId, onClose }: { kind: 'qui
|
|||
}
|
||||
};
|
||||
|
||||
const labels = { quiz: 'New quiz', deck: 'New flashcard deck', note: 'New note', folder: 'New folder' };
|
||||
const placeholders = { quiz: 'Cardiac medications', deck: 'Lab values', note: 'Exam 2 review', folder: 'Unit 3' };
|
||||
const labels = { quiz: 'New quiz', deck: 'New flashcard deck', note: 'New note', folder: `New ${groupLabel.toLowerCase()}` };
|
||||
const placeholders = { quiz: 'Cardiac medications', deck: 'Lab values', note: 'Exam 2 review', folder: `${groupLabel} 3` };
|
||||
return (
|
||||
<Dialog
|
||||
open={kind !== null}
|
||||
|
|
@ -280,7 +280,7 @@ const SHARE_BLURB: Record<ShareKind, string> = {
|
|||
deck: 'Anyone with the link can study these flashcards. They cannot change them.',
|
||||
note: 'Anyone with the link can read this note.',
|
||||
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 and view or download its documents.',
|
||||
folder: 'Anyone with the link can study the quizzes, decks and notes in this exam (or folder) and read or download its documents.',
|
||||
class: 'Anyone with the link can study every quiz, deck and note in this class and view or download its documents.',
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import type { AnswerState, SnapshotQuestion } from '@/lib/types';
|
|||
import { cx, formatDuration, formatMinutes, plural, useHotkeys, useLatest } from '@/lib/util';
|
||||
import { Markdown } from '@/ui/Markdown';
|
||||
import { Badge, Button, Dialog, IconButton, Input, ProgressBar, Segmented, useConfirm } from '@/ui';
|
||||
import { Ring } from './charts';
|
||||
import { ExplainSideContext } from './Explain';
|
||||
|
||||
/* ------------------------------ option list ------------------------------ */
|
||||
|
||||
|
|
@ -398,7 +398,7 @@ export function QuizRunner(p: RunnerProps) {
|
|||
<Markdown className="text-[15px]">{question.rationale}</Markdown>
|
||||
</div>
|
||||
)}
|
||||
{p.renderExtra?.(question, answerTexts(question, selected))}
|
||||
<ExplainSideContext.Provider value>{p.renderExtra?.(question, answerTexts(question, selected))}</ExplainSideContext.Provider>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
|
@ -482,6 +482,80 @@ export function QuizRunner(p: RunnerProps) {
|
|||
|
||||
/* ------------------------------ results ------------------------------ */
|
||||
|
||||
type ScoreTier = 'perfect' | 'a' | 'b' | 'c' | 'fail';
|
||||
|
||||
/** Bands of the 7-point scale: 93+ green, 85-92 blue, 77-84 yellow, below 77 (failing) red; 100% is a rainbow. */
|
||||
export function scoreTier(percent: number): ScoreTier {
|
||||
const p = Math.round(percent);
|
||||
return p >= 100 ? 'perfect' : p >= 93 ? 'a' : p >= 85 ? 'b' : p >= 77 ? 'c' : 'fail';
|
||||
}
|
||||
|
||||
const TIER_COLOR: Record<Exclude<ScoreTier, 'perfect'>, string> = { a: 'var(--good)', b: 'var(--accent)', c: 'var(--score-yellow)', fail: 'var(--bad)' };
|
||||
|
||||
/** The result ring: fills up and counts to the score; a perfect score cycles through a rainbow. */
|
||||
function ScoreRing({ percent, size = 136, stroke = 12 }: { percent: number; size?: number; stroke?: number }) {
|
||||
const tier = scoreTier(percent);
|
||||
const [shown, setShown] = useState(0);
|
||||
useEffect(() => {
|
||||
if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return setShown(percent);
|
||||
let frame = 0;
|
||||
const started = performance.now();
|
||||
const tick = (now: number) => {
|
||||
const t = Math.min(1, (now - started) / 1100);
|
||||
setShown(Math.round(percent * (1 - (1 - t) ** 3)));
|
||||
if (t < 1) frame = requestAnimationFrame(tick);
|
||||
};
|
||||
frame = requestAnimationFrame(tick);
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [percent]);
|
||||
const r = (size - stroke) / 2;
|
||||
const c = 2 * Math.PI * r;
|
||||
const gid = `score-${size}`;
|
||||
return (
|
||||
<div className="relative shrink-0" style={{ width: size, height: size }} role="img" aria-label={`Score ${percent} percent`}>
|
||||
<svg width={size} height={size} className={cx('-rotate-90', tier === 'perfect' && 'ring-rainbow')} aria-hidden>
|
||||
{tier === 'perfect' && (
|
||||
<defs>
|
||||
<linearGradient id={gid} x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0%" stopColor="#ff4d6d" />
|
||||
<stop offset="20%" stopColor="#ff9f1c" />
|
||||
<stop offset="40%" stopColor="#ffd60a" />
|
||||
<stop offset="60%" stopColor="#2ec27e" />
|
||||
<stop offset="80%" stopColor="#3a86ff" />
|
||||
<stop offset="100%" stopColor="#9b5de5" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
)}
|
||||
<circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="var(--line)" strokeWidth={stroke} />
|
||||
<circle
|
||||
cx={size / 2}
|
||||
cy={size / 2}
|
||||
r={r}
|
||||
fill="none"
|
||||
stroke={tier === 'perfect' ? `url(#${gid})` : TIER_COLOR[tier]}
|
||||
strokeWidth={stroke}
|
||||
strokeLinecap="round"
|
||||
strokeDasharray={c}
|
||||
strokeDashoffset={c * (1 - shown / 100)}
|
||||
/>
|
||||
</svg>
|
||||
<div className="absolute inset-0 grid place-items-center">
|
||||
<span className="num display text-[38px] leading-none font-medium">
|
||||
{shown}
|
||||
<span className="text-[20px] text-ink-3">%</span>
|
||||
</span>
|
||||
</div>
|
||||
{tier === 'perfect' && shown === 100 && (
|
||||
<span className="pointer-events-none absolute inset-0" aria-hidden>
|
||||
{[0, 1, 2, 3, 4, 5, 6, 7].map((i) => (
|
||||
<span key={i} className="score-spark absolute top-1/2 left-1/2 size-2 rounded-full" style={{ ['--a' as string]: `${i * 45}deg`, background: ['#ff4d6d', '#ff9f1c', '#ffd60a', '#2ec27e', '#3a86ff', '#9b5de5', '#ff4d6d', '#2ec27e'][i] }} />
|
||||
))}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export interface ResultsProps {
|
||||
title: string;
|
||||
mode: 'practice' | 'exam';
|
||||
|
|
@ -517,8 +591,6 @@ export function QuizResults(p: ResultsProps) {
|
|||
const partial = scored.filter((r) => !r.correct && r.score > 0).length;
|
||||
const wrong = scored.length - right - partial;
|
||||
const skipped = rows.length - scored.length;
|
||||
const tone = gradeToneFor(percent);
|
||||
const grade = letterGrade(percent);
|
||||
|
||||
const topics = useMemo(() => {
|
||||
const map = new Map<string, { n: number; s: number }>();
|
||||
|
|
@ -533,7 +605,8 @@ export function QuizResults(p: ResultsProps) {
|
|||
}, [scored]);
|
||||
|
||||
const visible = rows.filter((r) => (filter === 'all' ? true : filter === 'wrong' ? r.scored && !r.correct : p.flags.includes(r.q.id)));
|
||||
const headline = { A: 'Excellent work', B: 'Strong result', C: 'Passing', D: 'Just below passing', F: 'Worth another pass' }[grade];
|
||||
const tier = scoreTier(percent);
|
||||
const headline = { perfect: 'Perfect score!', a: 'Excellent work', b: 'Strong result', c: 'Passing', fail: 'Worth another pass' }[tier];
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh bg-paper">
|
||||
|
|
@ -548,14 +621,9 @@ export function QuizResults(p: ResultsProps) {
|
|||
<main className="mx-auto max-w-3xl animate-in px-4 pt-8 pb-24 sm:px-5">
|
||||
<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">
|
||||
<Ring value={percent / 100} size={128} stroke={11} tone={tone}>
|
||||
<div className="flex flex-col items-center leading-none">
|
||||
<span className="display text-[40px] font-medium">{grade}</span>
|
||||
<span className="num mt-1 text-[13px] font-medium text-ink-3">{percent}%</span>
|
||||
</div>
|
||||
</Ring>
|
||||
<ScoreRing percent={percent} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="eyebrow mb-1">{p.mode === 'exam' ? 'Exam result' : 'Practice result'} · grade {grade}</div>
|
||||
<div className="eyebrow mb-1">{p.mode === 'exam' ? 'Exam result' : 'Practice result'}</div>
|
||||
<h1 className="display text-[30px]">{headline}</h1>
|
||||
<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
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue