Second revision: MCP servers, shared-link AI, flashcard modes, document previews
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 30s
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 30s
Generation - Every quiz is NCLEX style; "Practice exam" writes 50 questions. - Calculation questions only when the material involves calculations (max 5 per exam). - Broad topics: the class's topics are listed in the prompt, a quick grouping call maps narrow labels onto broad ones, and leftover variants are merged. - Exact select-all count per batch; option order shuffled. - Python check: at most 3 runs, fixed problems count as passed, cosmetic remarks ignored. Assistant - Text, tool steps and cards appear in the order they happen, with paragraph breaks between steps. - Optional thinking box: fixed height, follows the newest text, can be scrolled back. - "+" opens a material picker listing recent items; items can be dragged in from class pages; shorter placeholder. MCP servers - Streamable HTTP client; encrypted headers. - Per-server instructions and switches for chat, Explain, generation and the quiz check. - Settings UI. Share links - Optional "Explain this" and "Ask about this material" per link, off by default. - Items are loaded on the server and checked against the share; no tools; rate-limited. - Migration 4 stores the switches. Study and documents - Standard flashcard mode (optionally repeat missed cards until known) next to spaced repetition. - Streak visuals restyled in the app palette. - Side by side / Original document views, with sandboxed previews of Word and PowerPoint files. Other - Built-in embedding model baked into the image; sharp stubbed if it cannot load; real load error shown in Settings. - Python runner blocks network and process modules in JavaScript too. - "View questions and answers" removed from the quiz start screen. - Docs updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
5ea61c882c
commit
031f7bec31
45 changed files with 2918 additions and 397 deletions
|
|
@ -4,6 +4,7 @@ import { useEffect, useMemo, useState } from 'react';
|
|||
import { toast } from 'sonner';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
import { qk } from '@/lib/queries';
|
||||
import { McpSettings } from './McpSettings';
|
||||
import { SemanticSettings } from './SemanticSettings';
|
||||
import { REASONING_EFFORTS, type AdapterMeta, type AiModel, type AiStatus, type Provider, type ProviderKind, type TaskConfig, type TaskName, type TaskSettings } from '@/lib/types';
|
||||
import { cx, formatCost, formatTokens, plural, timeAgo } from '@/lib/util';
|
||||
|
|
@ -739,6 +740,8 @@ export default function AiSettings() {
|
|||
|
||||
{providers.data.length > 0 && <SemanticSettings providers={providers.data} />}
|
||||
|
||||
{providers.data.length > 0 && <McpSettings />}
|
||||
|
||||
{providers.data.length > 0 && <Usage />}
|
||||
|
||||
<ProviderDialog open={dialog.open} onClose={() => setDialog((d) => ({ ...d, open: false }))} adapters={meta.data.adapters} existing={dialog.existing} onSaved={afterSave} />
|
||||
|
|
|
|||
|
|
@ -1,15 +1,52 @@
|
|||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { ArrowUp, AtSign, BookOpen, Check, ChevronDown, ChevronRight, CircleAlert, FileText, Folder, History, Layers, LoaderCircle, NotebookPen, Play, Plus, Sparkles, Square, Trash2, X } from 'lucide-react';
|
||||
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 { 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, useAssistantState } from '@/lib/assistantStore';
|
||||
import { assistant, ITEM_DRAG_TYPE, useAssistantState } from '@/lib/assistantStore';
|
||||
import { useAiModels, useAiStatus, useClasses, useRefresh } from '@/lib/queries';
|
||||
import type { AssistantEvent, ChatMessage, Mentionable, TaggedItem, TagKind, ToolActivity, UiItem } from '@/lib/types';
|
||||
import type { AssistantEvent, ChatMessage, 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 { Badge, Button, Callout, IconButton, Menu, MenuItem, MenuLabel, MenuSeparator, Spinner } from '@/ui';
|
||||
import { Badge, Button, Callout, IconButton, Input, Menu, MenuItem, MenuLabel, MenuSeparator, Popover, Spinner } from '@/ui';
|
||||
|
||||
|
||||
/** Applies one streamed event to a message. Text after a tool step or a new model step starts a new paragraph. */
|
||||
function reduceEvent(m: ChatMessage, e: AssistantEvent): ChatMessage {
|
||||
const parts = m.parts ? [...m.parts] : [];
|
||||
switch (e.type) {
|
||||
case 'start':
|
||||
return { ...m, model: e.model };
|
||||
case 'step': {
|
||||
const last = parts[parts.length - 1];
|
||||
if (last?.kind === 'text' && last.text) parts.push({ kind: 'text', text: '' });
|
||||
return { ...m, parts };
|
||||
}
|
||||
case 'text': {
|
||||
const last = parts[parts.length - 1];
|
||||
const fresh = last?.kind !== 'text';
|
||||
if (fresh) parts.push({ kind: 'text', text: e.delta });
|
||||
else parts[parts.length - 1] = { kind: 'text', text: last.text + e.delta };
|
||||
const startsBlock = fresh || (last?.kind === 'text' && last.text === '');
|
||||
return { ...m, parts, text: m.text + (startsBlock && m.text ? '\n\n' : '') + e.delta };
|
||||
}
|
||||
case 'reasoning':
|
||||
return { ...m, reasoning: (m.reasoning ?? '') + e.delta };
|
||||
case 'tool': {
|
||||
const known = m.tools.some((t) => t.id === e.tool.id);
|
||||
if (!known) parts.push({ kind: 'tool', id: e.tool.id });
|
||||
return { ...m, parts, tools: known ? m.tools.map((t) => (t.id === e.tool.id ? e.tool : t)) : [...m.tools, e.tool] };
|
||||
}
|
||||
case 'ui':
|
||||
parts.push({ kind: 'ui', index: m.ui.length });
|
||||
return { ...m, parts, ui: [...m.ui, e.item] };
|
||||
case 'error':
|
||||
return { ...m, error: e.message };
|
||||
default:
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
interface Conversation {
|
||||
id: string;
|
||||
|
|
@ -103,56 +140,123 @@ function ActionCard({ item, onResolved }: { item: Extract<UiItem, { type: 'actio
|
|||
);
|
||||
}
|
||||
|
||||
/** The model's reasoning, folded away by default: a short, scrollable window that follows the newest text. */
|
||||
function ReasoningBox({ text, live }: { text: string; live: boolean }) {
|
||||
const [open, setOpen] = useLocalStorage('sd.assistant.showReasoning', false);
|
||||
const box = useRef<HTMLDivElement>(null);
|
||||
const follow = useRef(true);
|
||||
// Very long reasoning is trimmed from the front so the box stays light.
|
||||
const shown = text.length > 24_000 ? `…${text.slice(-24_000)}` : text;
|
||||
useEffect(() => {
|
||||
const el = box.current;
|
||||
if (el && follow.current) el.scrollTop = el.scrollHeight;
|
||||
}, [shown, open]);
|
||||
return (
|
||||
<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">
|
||||
<Brain className={cx('size-3.5', live && 'animate-pulse text-accent')} />
|
||||
{open ? 'Hide thinking' : live ? 'Thinking… show' : 'Show thinking'}
|
||||
<ChevronRight className={cx('size-3.5 transition-transform', open && 'rotate-90')} />
|
||||
</button>
|
||||
{open && (
|
||||
<div
|
||||
ref={box}
|
||||
onScroll={(e) => {
|
||||
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"
|
||||
>
|
||||
{shown}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 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 }) {
|
||||
const navigate = useNavigate();
|
||||
const [toolsOpen, setToolsOpen] = useState(false);
|
||||
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]);
|
||||
const openCite = (c: Citation) => {
|
||||
onNavigate();
|
||||
navigate(`/documents/${c.documentId}?chunk=${c.chunkId}`);
|
||||
};
|
||||
const cards = message.ui.filter((u) => u.type !== 'sources');
|
||||
const running = message.tools.filter((t) => t.status === 'running');
|
||||
const finished = message.tools.filter((t) => t.status !== 'running');
|
||||
const thinking = message.pending && !message.text && running.length === 0;
|
||||
|
||||
// Text, tool steps and cards in the order they happened. Older messages without parts fall back to text first.
|
||||
const parts: MessagePart[] = message.parts?.length ? message.parts : [...(message.text ? [{ kind: 'text' as const, text: message.text }] : []), ...message.tools.map((t) => ({ kind: 'tool' as const, id: t.id })), ...message.ui.map((_, index) => ({ kind: 'ui' as const, index }))];
|
||||
const blocks: ({ kind: 'text'; text: string } | { kind: 'tools'; tools: ToolActivity[] } | { kind: 'ui'; item: UiItem })[] = [];
|
||||
for (const p of parts) {
|
||||
if (p.kind === 'text') {
|
||||
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;
|
||||
const last = blocks[blocks.length - 1];
|
||||
if (last?.kind === 'tools') last.tools.push(tool);
|
||||
else blocks.push({ kind: 'tools', tools: [tool] });
|
||||
} else {
|
||||
const item = message.ui[p.index];
|
||||
if (item && item.type !== 'sources') blocks.push({ kind: 'ui', item });
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2.5">
|
||||
{finished.length > 0 && (
|
||||
<div>
|
||||
<button type="button" aria-expanded={toolsOpen} onClick={() => setToolsOpen(!toolsOpen)} 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', toolsOpen && 'rotate-90')} />
|
||||
{finished.length === 1 ? finished[0].label : `${finished.length} steps`}
|
||||
{finished.some((t) => t.status === 'error') && <CircleAlert className="size-3.5 text-bad" />}
|
||||
</button>
|
||||
{toolsOpen && <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>
|
||||
{message.reasoning && <ReasoningBox text={message.reasoning} live={Boolean(message.pending) && !message.text} />}
|
||||
{blocks.map((b, i) =>
|
||||
b.kind === 'text' ? (
|
||||
<Markdown key={i} citations={citations} onCite={openCite} className="text-[15px]">
|
||||
{b.text}
|
||||
</Markdown>
|
||||
) : b.kind === 'tools' ? (
|
||||
<ToolGroup 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 === '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">
|
||||
<Play className="size-4 fill-current" />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate text-sm font-semibold">{b.item.title}</span>
|
||||
<ChevronRight className="size-4 text-ink-3" />
|
||||
</Link>
|
||||
) : null,
|
||||
)}
|
||||
{running.map((t) => (
|
||||
<ToolLine key={t.id} tool={t} />
|
||||
))}
|
||||
{thinking && (
|
||||
<div className="flex items-center gap-2 text-[13px] text-ink-3" role="status">
|
||||
<Spinner className="size-3.5" label="Thinking" /> {message.reasoning ? 'Thinking it through' : 'Thinking'}
|
||||
</div>
|
||||
)}
|
||||
{message.text && <Markdown citations={citations} onCite={openCite} className="text-[15px]">{message.text}</Markdown>}
|
||||
{cards.map((item, i) =>
|
||||
item.type === 'draft' ? (
|
||||
<DraftCard key={i} item={item} onNavigate={onNavigate} />
|
||||
) : item.type === 'action' ? (
|
||||
<ActionCard key={i} item={item} onResolved={(status, result) => onAction(item.actionId, status, result)} />
|
||||
) : item.type === 'link' ? (
|
||||
<Link key={i} to={`/${ITEM_URL[item.kind]}/${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">
|
||||
<Play className="size-4 fill-current" />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate text-sm font-semibold">{item.title}</span>
|
||||
<ChevronRight className="size-4 text-ink-3" />
|
||||
</Link>
|
||||
) : null,
|
||||
)}
|
||||
{cited.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5 pt-0.5">
|
||||
{cited.map(({ n, cite }) => (
|
||||
|
|
@ -242,7 +346,8 @@ function useMentionables(classId: string | null, query: string, enabled: boolean
|
|||
const q = useQuery({
|
||||
queryKey: ['ai', 'mentionables', classId ?? '', classId ? '' : debounced],
|
||||
queryFn: () => api.get<{ items: Mentionable[] }>(`/api/ai/mentionables?${new URLSearchParams(classId ? { classId } : { q: debounced })}`).then((r) => r.items),
|
||||
enabled: enabled && (Boolean(classId) || debounced.length >= 1),
|
||||
// An empty search lists the most recently changed materials, so the picker is useful before typing.
|
||||
enabled,
|
||||
staleTime: 30_000,
|
||||
});
|
||||
const needle = query.toLowerCase();
|
||||
|
|
@ -278,6 +383,9 @@ export default function AssistantPanel({
|
|||
const [tags, setTags] = useState<TaggedItem[]>([]);
|
||||
const [mention, setMention] = useState<{ start: number; query: string } | null>(null);
|
||||
const [mentionIndex, setMentionIndex] = useState(0);
|
||||
const [pickerOpen, setPickerOpen] = useState(false);
|
||||
const [pickerQuery, setPickerQuery] = useState('');
|
||||
const [dropping, setDropping] = useState(false);
|
||||
const [modelId, setModelId] = useLocalStorage('sd.assistant.model', '');
|
||||
/** The connection to the running turn. Aborting it only detaches: the turn continues on the server. */
|
||||
const stream = useRef<AbortController | null>(null);
|
||||
|
|
@ -301,16 +409,27 @@ export default function AssistantPanel({
|
|||
[variant],
|
||||
);
|
||||
|
||||
/** Applies one streamed event to the pending assistant message. */
|
||||
const applyEvent = useCallback((pendingId: string, e: AssistantEvent) => {
|
||||
const patch = (fn: (m: ChatMessage) => ChatMessage) => setMessages((list) => list.map((m) => (m.id === pendingId ? fn(m) : m)));
|
||||
if (e.type === 'start') patch((m) => ({ ...m, model: e.model }));
|
||||
else if (e.type === 'text') patch((m) => ({ ...m, text: m.text + e.delta }));
|
||||
else if (e.type === 'reasoning') patch((m) => ({ ...m, reasoning: (m.reasoning ?? '') + e.delta }));
|
||||
else if (e.type === 'tool') patch((m) => ({ ...m, tools: m.tools.some((t) => t.id === e.tool.id) ? m.tools.map((t) => (t.id === e.tool.id ? e.tool : t)) : [...m.tools, e.tool] }));
|
||||
else if (e.type === 'ui') patch((m) => ({ ...m, ui: [...m.ui, e.item] }));
|
||||
else if (e.type === 'error') patch((m) => ({ ...m, error: e.message }));
|
||||
/**
|
||||
* Streamed events are applied in batches (every 50 ms) rather than one render per token, so
|
||||
* long answers and reasoning do not make the page lag.
|
||||
*/
|
||||
const queued = useRef<{ id: string; e: AssistantEvent }[]>([]);
|
||||
const flushTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const flushEvents = useCallback(() => {
|
||||
if (flushTimer.current) clearTimeout(flushTimer.current);
|
||||
flushTimer.current = null;
|
||||
const batch = queued.current;
|
||||
queued.current = [];
|
||||
if (batch.length === 0) return;
|
||||
setMessages((list) => list.map((m) => batch.reduce((acc, { id, e }) => (id === m.id ? reduceEvent(acc, e) : acc), m)));
|
||||
}, []);
|
||||
const applyEvent = useCallback(
|
||||
(pendingId: string, e: AssistantEvent) => {
|
||||
queued.current.push({ id: pendingId, e });
|
||||
if (!flushTimer.current) flushTimer.current = setTimeout(flushEvents, 50);
|
||||
},
|
||||
[flushEvents],
|
||||
);
|
||||
|
||||
/** Follows a turn (new or already running) until it finishes or this panel detaches. */
|
||||
const follow = useCallback(
|
||||
|
|
@ -338,6 +457,7 @@ export default function AssistantPanel({
|
|||
} catch (e) {
|
||||
if ((e as Error)?.name !== 'AbortError') setMessages((list) => list.map((m) => (m.id === pendingId ? { ...m, error: errorMessage(e) } : m)));
|
||||
} finally {
|
||||
flushEvents();
|
||||
if (stream.current === controller) {
|
||||
stream.current = null;
|
||||
setBusy(false);
|
||||
|
|
@ -358,7 +478,7 @@ export default function AssistantPanel({
|
|||
void startedId;
|
||||
}
|
||||
},
|
||||
[applyEvent, onConversationChange, qc, refresh, setConversation],
|
||||
[applyEvent, flushEvents, onConversationChange, qc, refresh, setConversation],
|
||||
);
|
||||
|
||||
const load = useCallback(
|
||||
|
|
@ -377,7 +497,7 @@ export default function AssistantPanel({
|
|||
// Still answering: show what is saved up to the question, then replay the live turn.
|
||||
const lastUser = res.messages.map((m) => m.role).lastIndexOf('user');
|
||||
const pendingId = `p${Date.now()}`;
|
||||
setMessages([...res.messages.slice(0, lastUser + 1), { id: pendingId, role: 'assistant', text: '', tools: [], ui: [], createdAt: Date.now(), pending: true }]);
|
||||
setMessages([...res.messages.slice(0, lastUser + 1), { id: pendingId, role: 'assistant', text: '', tools: [], ui: [], parts: [], createdAt: Date.now(), pending: true }]);
|
||||
setLoadingHistory(false);
|
||||
void follow(pendingId, (signal, onEvent) => streamEvents<AssistantEvent>(`/api/ai/chat/${id}/stream`, undefined, onEvent, signal));
|
||||
} catch {
|
||||
|
|
@ -441,7 +561,7 @@ export default function AssistantPanel({
|
|||
setMessages((m) => [
|
||||
...m,
|
||||
{ id: `u${Date.now()}`, role: 'user', text: message, tags: sentTags.length ? sentTags : undefined, tools: [], ui: [], createdAt: Date.now() },
|
||||
{ id: pendingId, role: 'assistant', text: '', tools: [], ui: [], createdAt: Date.now(), pending: true },
|
||||
{ id: pendingId, role: 'assistant', text: '', tools: [], ui: [], parts: [], createdAt: Date.now(), pending: true },
|
||||
]);
|
||||
await follow(pendingId, (signal, onEvent) =>
|
||||
streamEvents<AssistantEvent>(
|
||||
|
|
@ -532,23 +652,42 @@ export default function AssistantPanel({
|
|||
}
|
||||
setMention(null);
|
||||
};
|
||||
const openPicker = () => {
|
||||
const el = inputRef.current;
|
||||
const caret = el?.selectionStart ?? input.length;
|
||||
const needsSpace = caret > 0 && !/\s/.test(input[caret - 1] ?? '');
|
||||
const next = `${input.slice(0, caret)}${needsSpace ? ' ' : ''}@${input.slice(caret)}`;
|
||||
setInput(next);
|
||||
const at = caret + (needsSpace ? 1 : 0) + 1;
|
||||
setMention({ start: at - 1, query: '' });
|
||||
setMentionIndex(0);
|
||||
setTimeout(() => {
|
||||
el?.focus();
|
||||
el?.setSelectionRange(at, at);
|
||||
}, 0);
|
||||
const pickerOptions = useMentionables(context.classId, pickerQuery, pickerOpen);
|
||||
const toggleTag = (item: TaggedItem) =>
|
||||
setTags((t) => (t.some((x) => x.kind === item.kind && x.id === item.id) ? t.filter((x) => !(x.kind === item.kind && x.id === item.id)) : [...t, { kind: item.kind, id: item.id, title: item.title }]));
|
||||
const onDrop = (e: React.DragEvent) => {
|
||||
setDropping(false);
|
||||
const raw = e.dataTransfer.getData(ITEM_DRAG_TYPE);
|
||||
if (!raw) return;
|
||||
e.preventDefault();
|
||||
try {
|
||||
const item = JSON.parse(raw) as TaggedItem;
|
||||
if (item?.id && item.kind) {
|
||||
setTags((t) => (t.some((x) => x.kind === item.kind && x.id === item.id) ? t : [...t, { kind: item.kind, id: item.id, title: item.title }]));
|
||||
inputRef.current?.focus();
|
||||
}
|
||||
} catch {
|
||||
/* not ours */
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col">
|
||||
<div
|
||||
className={cx('relative flex min-h-0 flex-1 flex-col', dropping && 'ring-2 ring-accent ring-inset')}
|
||||
onDragOver={(e) => {
|
||||
if (!e.dataTransfer.types.includes(ITEM_DRAG_TYPE)) return;
|
||||
e.preventDefault();
|
||||
e.dataTransfer.dropEffect = 'link';
|
||||
if (!dropping) setDropping(true);
|
||||
}}
|
||||
onDragLeave={(e) => {
|
||||
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setDropping(false);
|
||||
}}
|
||||
onDrop={onDrop}
|
||||
>
|
||||
{dropping && (
|
||||
<div className="pointer-events-none absolute inset-0 z-40 grid place-items-center bg-accent-soft/70 text-sm font-medium text-accent">Drop to add it to this chat</div>
|
||||
)}
|
||||
<header className={cx('flex h-14 shrink-0 items-center gap-2 border-b border-line px-3', variant === 'page' && 'lg:px-5')}>
|
||||
<span className="grid size-8 shrink-0 place-items-center rounded-[10px] bg-ink text-marker">
|
||||
<Sparkles className="size-4" />
|
||||
|
|
@ -625,7 +764,7 @@ export default function AssistantPanel({
|
|||
) : messages.length === 0 ? (
|
||||
<div className="mx-auto flex h-full max-w-md flex-col justify-center pb-6">
|
||||
<h2 className="display text-[26px]">What are we working on?</h2>
|
||||
<p className="mt-1.5 text-sm text-ink-2">I can read your documents, look at your results, and prepare quizzes, flashcards and study guides for you to review. Type @ to point me at a specific quiz, deck, note or document.</p>
|
||||
<p className="mt-1.5 text-sm text-ink-2">I can read your documents, look at your results, and prepare quizzes, flashcards and study guides for you to review. Use + (or type @, or drag items in) to point me at a specific quiz, deck, note or document.</p>
|
||||
<div className="mt-5 space-y-2">
|
||||
{suggestions.map((s) => (
|
||||
<button key={s} type="button" onClick={() => send(s)} className="group flex w-full items-center gap-3 rounded-[13px] border border-line bg-surface px-3.5 py-2.5 text-left text-sm shadow-1 hover:border-ink-3">
|
||||
|
|
@ -677,9 +816,9 @@ export default function AssistantPanel({
|
|||
)}
|
||||
{mention && (
|
||||
<div role="listbox" aria-label="Tag a material" className="absolute inset-x-0 bottom-full z-30 mb-2 max-h-72 overflow-y-auto rounded-xl border border-line bg-surface p-1.5 shadow-2">
|
||||
<div className="eyebrow px-2 pt-1 pb-1.5">{context.classId ? `Materials in ${className ?? 'this class'}` : 'Your library'}</div>
|
||||
<div className="eyebrow px-2 pt-1 pb-1.5">{context.classId ? `Materials in ${className ?? 'this class'}` : mention.query ? 'Your library' : 'Recently changed'}</div>
|
||||
{pickable.length === 0 ? (
|
||||
<div className="px-2.5 py-2 text-[13px] text-ink-3">{context.classId || mention.query ? 'Nothing matches.' : 'Type to search your quizzes, decks, notes and documents.'}</div>
|
||||
<div className="px-2.5 py-2 text-[13px] text-ink-3">{mention.query ? 'Nothing matches.' : 'Nothing in your library yet.'}</div>
|
||||
) : (
|
||||
pickable.map((o, i) => (
|
||||
<button
|
||||
|
|
@ -757,13 +896,57 @@ export default function AssistantPanel({
|
|||
if (!busy) void send(input);
|
||||
}
|
||||
}}
|
||||
placeholder={context.classId ? 'Ask anything. Type @ to tag a quiz, deck, note or document…' : 'Ask anything, or describe what to create…'}
|
||||
placeholder={variant === 'drawer' ? 'Ask anything…' : 'Ask anything, or describe what to create…'}
|
||||
aria-label="Message the assistant"
|
||||
className="max-h-44 min-h-9 flex-1 resize-none bg-transparent px-2.5 py-1.5 text-[15px] outline-none placeholder:text-ink-3"
|
||||
/>
|
||||
<IconButton label="Tag a material" size="sm" className="mb-0.5" onClick={openPicker}>
|
||||
<AtSign />
|
||||
</IconButton>
|
||||
<Popover
|
||||
open={pickerOpen}
|
||||
onOpenChange={(o) => {
|
||||
setPickerOpen(o);
|
||||
if (!o) setPickerQuery('');
|
||||
}}
|
||||
align="end"
|
||||
className="w-80 p-2"
|
||||
trigger={
|
||||
<IconButton label="Add materials" size="sm" className="mb-0.5" tooltip={false}>
|
||||
<Plus />
|
||||
</IconButton>
|
||||
}
|
||||
>
|
||||
<div className="relative mb-1.5">
|
||||
<Search className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-ink-3" aria-hidden />
|
||||
<Input autoFocus value={pickerQuery} onChange={(e) => setPickerQuery(e.target.value)} placeholder={context.classId ? `Search ${className ?? 'this class'}` : 'Search your library'} aria-label="Search materials" className="h-9 pl-8" />
|
||||
</div>
|
||||
<div role="listbox" aria-label="Materials" aria-multiselectable className="max-h-64 overflow-y-auto">
|
||||
{pickerOptions.length === 0 ? (
|
||||
<div className="px-2.5 py-3 text-[13px] text-ink-3">{pickerQuery ? 'Nothing matches.' : 'Nothing in your library yet.'}</div>
|
||||
) : (
|
||||
pickerOptions.map((o) => {
|
||||
const on = tags.some((t) => t.kind === o.kind && t.id === o.id);
|
||||
return (
|
||||
<button key={`${o.kind}:${o.id}`} type="button" role="option" aria-selected={on} onClick={() => toggleTag(o)} className="flex w-full items-center gap-2.5 rounded-lg px-2 py-1.5 text-left hover:bg-ink/6">
|
||||
<span className={cx('grid size-7 shrink-0 place-items-center rounded-md [&>svg]:size-3.5', on ? 'bg-accent text-accent-ink' : 'bg-sunken text-ink-2')}>{on ? <Check /> : TAG_ICON[o.kind]}</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-sm">{o.title}</span>
|
||||
<span className="block truncate text-[11px] text-ink-3">
|
||||
{TAG_NOUN[o.kind]}
|
||||
{o.folderName ? ` · ${o.folderName}` : ''}
|
||||
{!context.classId ? ` · ${o.className}` : ''}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-1.5 flex items-center justify-between border-t border-line px-1 pt-1.5 text-[11px] text-ink-3">
|
||||
<span>{tags.length ? `${plural(tags.length, 'item')} added` : 'Tip: type @ in the message, or drag items here'}</span>
|
||||
<button type="button" className="font-medium text-accent hover:underline" onClick={() => setPickerOpen(false)}>
|
||||
Done
|
||||
</button>
|
||||
</div>
|
||||
</Popover>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!busy && !input.trim()}
|
||||
|
|
|
|||
|
|
@ -7,12 +7,15 @@ import { Button, Callout, Spinner } from '@/ui';
|
|||
type ExplainBody =
|
||||
| { kind: 'question'; stem: string; options: { text: string; correct: boolean }[]; selected?: string[]; rationale?: string }
|
||||
| { kind: 'card'; front: string; back: string }
|
||||
| { kind: 'text'; text: 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' };
|
||||
|
||||
/** "Explain with AI": streams a short explanation and accepts follow-up questions. */
|
||||
export function Explain({ body, label = 'Explain with AI', className }: { body: ExplainBody; label?: string; className?: string }) {
|
||||
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 [busy, setBusy] = useState(false);
|
||||
|
|
@ -40,7 +43,7 @@ export function Explain({ body, label = 'Explain with AI', className }: { body:
|
|||
abort.current = controller;
|
||||
try {
|
||||
await streamEvents<Event>(
|
||||
'/api/ai/explain',
|
||||
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)));
|
||||
|
|
|
|||
|
|
@ -36,7 +36,7 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
|
|||
const [text, setText] = useState('');
|
||||
const [focus, setFocus] = useState('');
|
||||
const [count, setCount] = useState(15);
|
||||
const [style, setStyle] = useState<'nclex' | 'standard' | 'recall'>('nclex');
|
||||
const [format, setFormat] = useState<'practice' | 'exam'>('practice');
|
||||
const [difficulty, setDifficulty] = useState<'mixed' | 'easy' | 'medium' | 'hard'>('mixed');
|
||||
const [sata, setSata] = useState(30);
|
||||
const [cardStyle, setCardStyle] = useState<'concise' | 'detailed' | 'medication' | 'definition'>('concise');
|
||||
|
|
@ -62,7 +62,7 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
|
|||
setTemplateId('');
|
||||
setModelId('');
|
||||
setCount(k === 'deck' ? 30 : 15);
|
||||
setStyle('nclex');
|
||||
setFormat('practice');
|
||||
setDifficulty('mixed');
|
||||
setSata(30);
|
||||
setCardStyle('concise');
|
||||
|
|
@ -81,7 +81,7 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
|
|||
const p = t.payload;
|
||||
if (p.kind && !preset?.kind) setKind(p.kind);
|
||||
if (typeof p.count === 'number') setCount(p.count);
|
||||
if (p.style) setStyle(p.style);
|
||||
if (p.kind === 'quiz') setFormat(p.format === 'exam' ? 'exam' : 'practice');
|
||||
if (p.difficulty) setDifficulty(p.difficulty);
|
||||
if (typeof p.sataShare === 'number') setSata(Math.round(p.sataShare * 100));
|
||||
if (p.cardStyle) setCardStyle(p.cardStyle);
|
||||
|
|
@ -104,7 +104,7 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
|
|||
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 };
|
||||
if (kind === 'quiz') Object.assign(body, { count, style, difficulty, sataShare: sata / 100, verify });
|
||||
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 });
|
||||
if (fixedSource && kind !== 'note') delete body.count;
|
||||
|
|
@ -247,12 +247,20 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
|
|||
<Input type="number" min={1} max={100} value={count} onChange={(e) => setCount(Math.max(1, Math.min(100, Number(e.target.value) || 1)))} />
|
||||
</Field>
|
||||
)}
|
||||
<Field label="Style">
|
||||
<Select value={style} onChange={(e) => setStyle(e.target.value as typeof style)}>
|
||||
<option value="nclex">NCLEX-style (clinical judgment)</option>
|
||||
<option value="standard">Standard exam questions</option>
|
||||
<option value="recall">Quick recall</option>
|
||||
</Select>
|
||||
<Field label="Set" hint={format === 'exam' ? 'Like a unit exam: 50 questions, up to 5 calculations when the material has them.' : 'All questions are NCLEX style.'}>
|
||||
<Segmented
|
||||
label="Set"
|
||||
value={format}
|
||||
onChange={(f) => {
|
||||
setFormat(f);
|
||||
setCount(f === 'exam' ? 50 : 15);
|
||||
}}
|
||||
options={[
|
||||
{ value: 'practice', label: 'Practice set' },
|
||||
{ value: 'exam', label: 'Practice exam' },
|
||||
]}
|
||||
className="w-full"
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Difficulty">
|
||||
<Select value={difficulty} onChange={(e) => setDifficulty(e.target.value as typeof difficulty)}>
|
||||
|
|
|
|||
257
web/src/features/McpSettings.tsx
Normal file
257
web/src/features/McpSettings.tsx
Normal file
|
|
@ -0,0 +1,257 @@
|
|||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { CircleAlert, CircleCheck, Plug, Plus, Trash2 } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
import { Badge, Button, Dialog, Field, Input, Section, Switch, Textarea, useConfirm } from '@/ui';
|
||||
|
||||
type McpArea = 'chat' | 'explain' | 'generate' | 'check';
|
||||
type McpAreas = Record<McpArea, boolean>;
|
||||
|
||||
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.' },
|
||||
{ key: 'check', label: 'Quiz check', description: 'The answer check after a quiz is generated.' },
|
||||
];
|
||||
const DEFAULT_AREAS: McpAreas = { chat: true, explain: true, generate: false, check: false };
|
||||
|
||||
interface McpServer {
|
||||
id: string;
|
||||
name: string;
|
||||
url: string;
|
||||
enabled: boolean;
|
||||
instructions: string;
|
||||
areas: McpAreas;
|
||||
headerNames: string[];
|
||||
lastTestAt: number | null;
|
||||
lastTestOk: boolean | null;
|
||||
lastTestMessage: string | null;
|
||||
}
|
||||
|
||||
interface TestResult {
|
||||
ok: boolean;
|
||||
message: string;
|
||||
tools: { name: string; description: string }[];
|
||||
latencyMs: number;
|
||||
}
|
||||
|
||||
const KEY = ['ai', 'mcp'];
|
||||
|
||||
function parseHeaders(text: string): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
for (const line of text.split('\n')) {
|
||||
const at = line.indexOf(':');
|
||||
if (at > 0) out[line.slice(0, at).trim()] = line.slice(at + 1).trim();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function ServerDialog({ open, existing, onClose, onSaved }: { open: boolean; existing: McpServer | null; onClose: () => void; onSaved: (s: McpServer) => void }) {
|
||||
const [name, setName] = useState('');
|
||||
const [url, setUrl] = useState('');
|
||||
const [headers, setHeaders] = useState('');
|
||||
const [instructions, setInstructions] = useState('');
|
||||
const [areas, setAreas] = useState<McpAreas>(DEFAULT_AREAS);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setName(existing?.name ?? '');
|
||||
setUrl(existing?.url ?? '');
|
||||
setHeaders('');
|
||||
setInstructions(existing?.instructions ?? '');
|
||||
setAreas(existing?.areas ?? DEFAULT_AREAS);
|
||||
}, [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 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();
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={existing ? `Edit ${existing.name}` : 'Connect an MCP server'}
|
||||
description="The assistant can call this server's tools. Only connect servers you trust: their tools run without asking."
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" loading={busy} disabled={!canSave} onClick={save}>
|
||||
{existing ? 'Save' : 'Connect'}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<form
|
||||
className="space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (canSave) void save();
|
||||
}}
|
||||
>
|
||||
<Field label="Name" hint="Shown next to each tool the assistant uses.">
|
||||
<Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Drug reference" maxLength={60} />
|
||||
</Field>
|
||||
<Field label="Server URL" hint="The Streamable HTTP endpoint, usually ending in /mcp. From inside Docker, use your server's address rather than localhost.">
|
||||
<Input value={url} onChange={(e) => setUrl(e.target.value)} placeholder="https://example.com/mcp" inputMode="url" spellCheck={false} className="num text-[13px]" />
|
||||
</Field>
|
||||
<Field label="When to use it" optional hint="Your guidance for the AI, for example: Use for current drug information. Do not use for questions my course material already answers.">
|
||||
<Textarea rows={3} value={instructions} onChange={(e) => setInstructions(e.target.value)} maxLength={2000} placeholder="Use this to look up…" />
|
||||
</Field>
|
||||
<fieldset className="space-y-3 rounded-xl border border-line p-3.5">
|
||||
<legend className="px-1 text-sm font-medium text-ink">Where it can be used</legend>
|
||||
{AREAS.map((a) => (
|
||||
<Switch key={a.key} checked={areas[a.key]} onChange={(v) => setAreas((s) => ({ ...s, [a.key]: v }))} label={a.label} description={a.description} />
|
||||
))}
|
||||
</fieldset>
|
||||
<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>
|
||||
<button type="submit" hidden />
|
||||
</form>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function ServerRow({ server, onEdit, reload }: { server: McpServer; onEdit: () => void; reload: () => void }) {
|
||||
const confirm = useConfirm();
|
||||
const [testing, setTesting] = useState(false);
|
||||
const [tools, setTools] = useState<TestResult['tools'] | null>(null);
|
||||
|
||||
const test = async () => {
|
||||
setTesting(true);
|
||||
try {
|
||||
const { result } = await api.post<{ result: TestResult }>(`/api/ai/mcp/${server.id}/test`);
|
||||
if (result.ok) {
|
||||
toast.success(result.message);
|
||||
setTools(result.tools);
|
||||
} else toast.error(result.message);
|
||||
reload();
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
} finally {
|
||||
setTesting(false);
|
||||
}
|
||||
};
|
||||
const toggle = async (enabled: boolean) => {
|
||||
try {
|
||||
await api.patch(`/api/ai/mcp/${server.id}`, { enabled });
|
||||
reload();
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
}
|
||||
};
|
||||
const remove = async () => {
|
||||
if (!(await confirm({ title: `Remove ${server.name}?`, message: 'The assistant will no longer see its tools.', confirmLabel: 'Remove', danger: true }))) return;
|
||||
try {
|
||||
await api.del(`/api/ai/mcp/${server.id}`);
|
||||
reload();
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-4">
|
||||
<div className="flex flex-wrap items-start gap-3">
|
||||
<span className="grid size-9 shrink-0 place-items-center rounded-[10px] bg-sunken text-ink-2">
|
||||
<Plug className="size-4" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="font-semibold">{server.name}</div>
|
||||
<div className="num truncate text-xs text-ink-3">{server.url}</div>
|
||||
<div className="mt-1.5 flex flex-wrap gap-1">
|
||||
{AREAS.filter((a) => server.areas[a.key]).map((a) => (
|
||||
<Badge key={a.key}>{a.label}</Badge>
|
||||
))}
|
||||
{!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.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" />}
|
||||
<span className="min-w-0 break-words">{server.lastTestMessage}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Switch checked={server.enabled} onChange={toggle} label={<span className="sr-only">Use {server.name}</span>} />
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<Button size="sm" variant="secondary" loading={testing} onClick={test}>
|
||||
Test and list tools
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={onEdit}>
|
||||
Edit
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" icon={<Trash2 />} onClick={remove} className="ml-auto text-bad">
|
||||
Remove
|
||||
</Button>
|
||||
</div>
|
||||
{tools && (
|
||||
<ul className="mt-3 space-y-1 rounded-[10px] border border-line bg-sunken/50 p-3 text-xs">
|
||||
{tools.length === 0 && <li className="text-ink-3">This server has no tools.</li>}
|
||||
{tools.map((t) => (
|
||||
<li key={t.name}>
|
||||
<span className="num font-medium text-ink">{t.name}</span>
|
||||
{t.description && <span className="text-ink-3"> · {t.description}</span>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** MCP servers: external tools the assistant can call. */
|
||||
export function McpSettings() {
|
||||
const qc = useQueryClient();
|
||||
const q = useQuery({ queryKey: KEY, queryFn: () => api.get<{ servers: McpServer[] }>('/api/ai/mcp') });
|
||||
const [dialog, setDialog] = useState<{ open: boolean; existing: McpServer | null }>({ open: false, existing: null });
|
||||
const reload = () => qc.invalidateQueries({ queryKey: KEY });
|
||||
const servers = q.data?.servers ?? [];
|
||||
|
||||
return (
|
||||
<Section
|
||||
title="MCP servers"
|
||||
action={
|
||||
<Button size="sm" variant="secondary" icon={<Plus />} onClick={() => setDialog({ open: true, existing: null })}>
|
||||
Add server
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{servers.length > 0 ? (
|
||||
<div className="card divide-y divide-line">
|
||||
{servers.map((s) => (
|
||||
<ServerRow key={s.id} server={s} onEdit={() => setDialog({ open: true, existing: s })} reload={reload} />
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<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>
|
||||
<ServerDialog
|
||||
open={dialog.open}
|
||||
existing={dialog.existing}
|
||||
onClose={() => setDialog((d) => ({ ...d, open: false }))}
|
||||
onSaved={(s) => {
|
||||
void reload();
|
||||
if (!dialog.existing) toast.success(`Added ${s.name}. Test it to see its tools.`);
|
||||
}}
|
||||
/>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
|
@ -145,6 +145,11 @@ export function SemanticSettings({ providers }: { providers: Provider[] }) {
|
|||
{data.local.status === 'loading' ? ' Loading the model now…' : ''}
|
||||
</p>
|
||||
)}
|
||||
{isLocal && data.local.status === 'error' && data.local.error && (
|
||||
<Callout tone="bad" icon={<CircleAlert />} className="mt-3" title="The built-in model could not load">
|
||||
{data.local.error}
|
||||
</Callout>
|
||||
)}
|
||||
{eligible.length === 0 && !isLocal && (
|
||||
<Callout tone="accent" icon={<Sparkles />} className="mt-3" title="Cloud embeddings need a provider">
|
||||
Use the built-in model, or connect OpenAI, Gemini, Ollama or an OpenAI-compatible server above. Anthropic and DeepSeek do not offer embeddings.
|
||||
|
|
|
|||
129
web/src/features/SharedAssistant.tsx
Normal file
129
web/src/features/SharedAssistant.tsx
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
import { CornerDownLeft, MessageCircleQuestion, Sparkles, Square, X } from 'lucide-react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { errorMessage, streamEvents } from '@/lib/api';
|
||||
import { cx } from '@/lib/util';
|
||||
import { Markdown } from '@/ui/Markdown';
|
||||
import { Button, Callout, IconButton, Spinner } from '@/ui';
|
||||
|
||||
type Event = { type: 'text'; delta: string } | { type: 'error'; message: string } | { type: 'done' };
|
||||
interface Turn {
|
||||
role: 'user' | 'assistant';
|
||||
text: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export function SharedAssistant({ token, title, item }: { token: string; title: string; item?: { kind: 'quiz' | 'deck' | 'note' | 'document'; id: string } }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [turns, setTurns] = useState<Turn[]>([]);
|
||||
const [input, setInput] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const abort = useRef<AbortController | null>(null);
|
||||
const list = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => () => abort.current?.abort(), []);
|
||||
useEffect(() => {
|
||||
const el = list.current;
|
||||
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));
|
||||
}
|
||||
};
|
||||
|
||||
if (!open) {
|
||||
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>
|
||||
);
|
||||
}
|
||||
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" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-sm font-semibold">Ask about this</div>
|
||||
<div className="truncate text-xs text-ink-3">{title}</div>
|
||||
</div>
|
||||
<IconButton label="Close" onClick={() => setOpen(false)}>
|
||||
<X />
|
||||
</IconButton>
|
||||
</header>
|
||||
<div ref={list} className="flex-1 space-y-3 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,
|
||||
)}
|
||||
{error && (
|
||||
<Callout tone="bad" className="py-2">
|
||||
{error}
|
||||
</Callout>
|
||||
)}
|
||||
</div>
|
||||
<form
|
||||
className="flex gap-2 border-t border-line p-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (busy) return abort.current?.abort();
|
||||
const text = input.trim();
|
||||
if (!text) return;
|
||||
setInput('');
|
||||
void send(text.slice(0, 4000));
|
||||
}}
|
||||
>
|
||||
<input
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
placeholder="Ask a question…"
|
||||
aria-label="Your question"
|
||||
className={cx('h-10 min-w-0 flex-1 rounded-[10px] border border-line-strong bg-paper px-3 text-sm outline-none focus:border-accent')}
|
||||
/>
|
||||
<Button type="submit" variant={busy ? 'secondary' : 'primary'} icon={busy ? <Square className="fill-current" /> : <CornerDownLeft />} aria-label={busy ? 'Stop' : 'Send'}>
|
||||
{busy ? 'Stop' : 'Send'}
|
||||
</Button>
|
||||
</form>
|
||||
<p className="px-4 pb-2.5 text-[11px] text-ink-3">AI can be wrong. Nothing you type here is saved.</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -154,7 +154,7 @@ function PresetDialog({ template, onClose }: { template: Template | null; onClos
|
|||
setBusy(true);
|
||||
try {
|
||||
const clean = { ...payload };
|
||||
if (kind !== 'quiz') ['style', 'difficulty', 'sataShare'].forEach((k) => delete clean[k]);
|
||||
if (kind !== 'quiz') ['style', 'format', 'difficulty', 'sataShare'].forEach((k) => delete clean[k]);
|
||||
if (kind !== 'deck') delete clean.cardStyle;
|
||||
if (kind !== 'note') delete clean.noteStyle;
|
||||
if (kind === 'note') delete clean.count;
|
||||
|
|
@ -210,11 +210,10 @@ function PresetDialog({ template, onClose }: { template: Template | null; onClos
|
|||
)}
|
||||
{kind === 'quiz' && (
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
<Field label="Style">
|
||||
<Select value={payload.style ?? 'nclex'} onChange={(e) => set({ style: e.target.value })}>
|
||||
<option value="nclex">NCLEX</option>
|
||||
<option value="standard">Standard</option>
|
||||
<option value="recall">Quick recall</option>
|
||||
<Field label="Set">
|
||||
<Select value={payload.format ?? 'practice'} onChange={(e) => set({ format: e.target.value, style: 'nclex', ...(e.target.value === 'exam' && !payload.count ? { count: 50 } : {}) })}>
|
||||
<option value="practice">Practice set</option>
|
||||
<option value="exam">Practice exam</option>
|
||||
</Select>
|
||||
</Field>
|
||||
<Field label="Difficulty">
|
||||
|
|
|
|||
|
|
@ -362,6 +362,22 @@ export function ShareDialog({ target, onClose }: { target: { kind: ShareKind; id
|
|||
</span>
|
||||
</div>
|
||||
<p className="text-[13px] text-ink-3">"New link" replaces the address, so the old one stops working. Visitors study on their own; nothing they do touches your progress.</p>
|
||||
<fieldset className="space-y-3.5 rounded-xl border border-line p-4">
|
||||
<legend className="px-1 text-sm font-medium text-ink">AI for visitors</legend>
|
||||
<Switch
|
||||
checked={Boolean(share.ai?.explain)}
|
||||
onChange={(v) => act(() => api.patch<{ share: Share }>(`/api/shares/${share.id}`, { ai: { explain: v } }))}
|
||||
label="Explain this"
|
||||
description="Visitors can ask the AI to explain a question or flashcard."
|
||||
/>
|
||||
<Switch
|
||||
checked={Boolean(share.ai?.assistant)}
|
||||
onChange={(v) => act(() => api.patch<{ share: Share }>(`/api/shares/${share.id}`, { ai: { assistant: v } }))}
|
||||
label="Ask about this material"
|
||||
description="A chat that answers from what you shared only. It can't see the rest of your library or your connected tools."
|
||||
/>
|
||||
<p className="text-xs text-ink-3">Uses your AI models and is billed to your API keys. Requests are rate-limited per visitor.</p>
|
||||
</fieldset>
|
||||
</>
|
||||
) : (
|
||||
<Callout icon={<Link2Off />}>{share ? 'The link is off. Anyone who has it sees a "no longer available" page.' : 'Sharing is off. Nobody else can see this.'}</Callout>
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { ArrowLeft, Check, Lightbulb, RotateCcw, Shuffle, SkipForward, X } from 'lucide-react';
|
||||
import { useCallback, useEffect, useId, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react';
|
||||
import { ArrowLeft, Check, Flame, Lightbulb, RotateCcw, Shuffle, SkipForward, X } from 'lucide-react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react';
|
||||
import { cx, plural, shuffle, useHotkeys } from '@/lib/util';
|
||||
import { Markdown } from '@/ui/Markdown';
|
||||
import { Button, IconButton, ProgressBar } from '@/ui';
|
||||
|
|
@ -14,49 +14,31 @@ export const STREAK_HOT = 5;
|
|||
export const isStreakMilestone = (n: number) => n === 5 || (n >= 10 && n % 10 === 0);
|
||||
export const streakTier = (n: number): StreakTier => (n >= 20 ? 3 : n >= 10 ? 2 : 1);
|
||||
const BURST_MS: Record<StreakTier, number> = { 1: 1600, 2: 1900, 3: 2400 };
|
||||
const BURST_COPY: Record<StreakTier, string> = { 1: 'On fire', 2: 'Blazing', 3: 'Unstoppable' };
|
||||
|
||||
export function FlameIcon({ className }: { className?: string }) {
|
||||
const id = `flame-${useId().replace(/[^a-zA-Z0-9]/g, '')}`;
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 24 24" aria-hidden focusable="false">
|
||||
<defs>
|
||||
<linearGradient id={id} x1="0" y1="1" x2="0" y2="0">
|
||||
<stop offset="0%" stopColor="#ea580c" />
|
||||
<stop offset="55%" stopColor="#fb923c" />
|
||||
<stop offset="100%" stopColor="#fbbf24" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path
|
||||
fill={`url(#${id})`}
|
||||
fillRule="evenodd"
|
||||
clipRule="evenodd"
|
||||
d="M12.963 2.286a.75.75 0 0 0-1.071-.136 9.742 9.742 0 0 0-3.539 6.177A7.547 7.547 0 0 1 6.648 6.61a.75.75 0 0 0-1.152-.082A9 9 0 1 0 15.68 4.534a7.46 7.46 0 0 1-2.717-2.248ZM15.75 14.25a3.75 3.75 0 1 1-7.313-1.172c.628.465 1.35.81 2.133 1a5.99 5.99 0 0 1 1.925-3.547 3.75 3.75 0 0 1 3.255 3.719Z"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
const BURST_COPY: Record<StreakTier, string> = { 1: 'On a roll', 2: 'Hot streak', 3: 'Unstoppable' };
|
||||
|
||||
export function StreakChip({ streak }: { streak: number }) {
|
||||
if (streak < 2) return null;
|
||||
const hot = streak >= STREAK_HOT;
|
||||
return (
|
||||
<span key={hot ? 'hot' : 'warm'} className={cx('streak-chip inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-xs font-bold whitespace-nowrap', hot ? 'streak-chip-hot' : 'bg-ink/7 text-ink-2')}>
|
||||
{hot && <FlameIcon className="size-3.5 shrink-0" />}
|
||||
<span key={hot ? 'hot' : 'warm'} className={cx('streak-chip num inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-xs font-semibold whitespace-nowrap', hot ? 'streak-chip-hot' : 'bg-ink/7 text-ink-2')}>
|
||||
{hot && <Flame className="size-3.5 shrink-0" strokeWidth={2.4} />}
|
||||
{streak} in a row
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** Milestone moment: the count, marked with a highlighter stroke, in the app's own type and colours. */
|
||||
function StreakBurst({ streak, tier }: { streak: number; tier: StreakTier }) {
|
||||
const flame = { 1: 'size-16', 2: 'size-24', 3: 'size-36 md:size-44' }[tier];
|
||||
const heading = { 1: 'text-lg', 2: 'text-2xl', 3: 'text-4xl md:text-5xl' }[tier];
|
||||
const size = { 1: 'text-6xl', 2: 'text-7xl', 3: 'text-8xl md:text-9xl' }[tier];
|
||||
return (
|
||||
<div className="streak-scrim pointer-events-none absolute inset-0 z-30 flex items-center justify-center rounded-[24px]" style={{ '--streak-ms': `${BURST_MS[tier]}ms` } as CSSProperties} role="status" aria-live="polite">
|
||||
<div className="streak-pop flex flex-col items-center">
|
||||
<FlameIcon className={cx('streak-flame', flame)} />
|
||||
<span className={cx('streak-heading mt-1 font-black tracking-wide uppercase', heading)}>{BURST_COPY[tier]}</span>
|
||||
<span className="mt-1 text-sm font-semibold text-ink">{streak} in a row</span>
|
||||
<div className="streak-pop flex flex-col items-center text-center">
|
||||
<span className="flex items-center gap-1.5 text-xs font-semibold tracking-[0.16em] text-accent uppercase">
|
||||
<Flame className="streak-flame size-4" strokeWidth={2.4} />
|
||||
{BURST_COPY[tier]}
|
||||
</span>
|
||||
<span className={cx('streak-mark num mt-2 px-4 leading-none font-semibold tracking-tight text-ink', size)}>{streak}</span>
|
||||
<span className="mt-2 font-serif text-xl text-ink-2 italic">in a row</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
|
@ -250,6 +232,10 @@ export interface CramState {
|
|||
shuffled: boolean;
|
||||
/** Which pass this is: 1 = whole deck, 2+ = cards still being learned. */
|
||||
round: number;
|
||||
/** Standard mode option: a missed card goes to the back of the pile until it is known. */
|
||||
repeatMissed?: boolean;
|
||||
/** Cards that were missed at least once in this session (repeat mode). */
|
||||
retried?: string[];
|
||||
}
|
||||
|
||||
export interface CramCard {
|
||||
|
|
@ -259,9 +245,9 @@ export interface CramCard {
|
|||
hint?: string;
|
||||
}
|
||||
|
||||
export function freshCramState(cards: CramCard[], shuffled: boolean, round = 1): CramState {
|
||||
export function freshCramState(cards: CramCard[], shuffled: boolean, round = 1, repeatMissed = false): CramState {
|
||||
const ids = cards.map((c) => c.id);
|
||||
return { order: shuffled ? shuffle(ids) : ids, index: 0, known: [], unknown: [], shuffled, round };
|
||||
return { order: shuffled ? shuffle(ids) : ids, index: 0, known: [], unknown: [], shuffled, round, repeatMissed, retried: [] };
|
||||
}
|
||||
|
||||
/** Drops cards that no longer exist and clamps the position, so a saved session survives deck edits. */
|
||||
|
|
@ -277,6 +263,8 @@ export function reconcileCramState(state: CramState | null | undefined, cards: C
|
|||
unknown: (state.unknown ?? []).filter((id) => valid.has(id)),
|
||||
shuffled: Boolean(state.shuffled),
|
||||
round: state.round ?? 1,
|
||||
repeatMissed: Boolean(state.repeatMissed),
|
||||
retried: (state.retried ?? []).filter((id) => valid.has(id)),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -328,9 +316,13 @@ export function CramSession({
|
|||
setLeaving(known ? 'right' : 'left');
|
||||
record(known);
|
||||
onGrade?.(card.id, known);
|
||||
// Repeat mode: a missed card goes to the back of the pile and comes round again.
|
||||
const requeue = !known && state.repeatMissed;
|
||||
const next: CramState = {
|
||||
...state,
|
||||
index: state.index + 1,
|
||||
order: requeue ? [...state.order, card.id] : state.order,
|
||||
retried: requeue ? [...new Set([...(state.retried ?? []), card.id])] : state.retried,
|
||||
known: known ? [...state.known.filter((x) => x !== card.id), card.id] : state.known.filter((x) => x !== card.id),
|
||||
unknown: known ? state.unknown.filter((x) => x !== card.id) : [...state.unknown.filter((x) => x !== card.id), card.id],
|
||||
};
|
||||
|
|
@ -339,7 +331,7 @@ export function CramSession({
|
|||
const move = (delta: number) => !busy && onState({ ...state, index: Math.max(0, Math.min(total, state.index + delta)) });
|
||||
const restart = (shuffled = state.shuffled) => {
|
||||
reset();
|
||||
onState(freshCramState(cards, shuffled));
|
||||
onState(freshCramState(cards, shuffled, 1, state.repeatMissed));
|
||||
};
|
||||
const shuffleRemaining = () => {
|
||||
if (busy) return;
|
||||
|
|
@ -351,7 +343,7 @@ export function CramSession({
|
|||
};
|
||||
const studyUnknown = () => {
|
||||
reset();
|
||||
onState(freshCramState(cards.filter((c) => state.unknown.includes(c.id)), true, state.round + 1));
|
||||
onState(freshCramState(cards.filter((c) => state.unknown.includes(c.id)), true, state.round + 1, state.repeatMissed));
|
||||
};
|
||||
|
||||
useHotkeys({
|
||||
|
|
@ -371,7 +363,7 @@ export function CramSession({
|
|||
<div className="flex min-h-dvh flex-col bg-paper">
|
||||
<StudyTopBar
|
||||
title={title}
|
||||
subtitle={subtitle ?? (state.round > 1 ? `Round ${state.round}: still learning` : 'Browse')}
|
||||
subtitle={subtitle ?? (state.round > 1 ? `Round ${state.round}: still learning` : state.repeatMissed ? 'Standard · missed cards repeat' : 'Standard')}
|
||||
onExit={onExit}
|
||||
exitLabel={exitLabel}
|
||||
progress={total ? Math.min(1, state.index / total) : 0}
|
||||
|
|
@ -398,7 +390,9 @@ export function CramSession({
|
|||
</div>
|
||||
<h2 className="display text-[28px]">{state.unknown.length === 0 ? 'You know them all' : 'Round complete'}</h2>
|
||||
<p className="mt-2 text-[15px] text-ink-2">
|
||||
{state.known.length} known{state.unknown.length > 0 ? `, ${state.unknown.length} still learning` : ''} out of {plural(total, 'card')}.
|
||||
{state.repeatMissed
|
||||
? `All ${plural(state.known.length, 'card')} known${state.retried?.length ? `; ${state.retried.length} took more than one try` : ' on the first try'}.`
|
||||
: `${state.known.length} known${state.unknown.length > 0 ? `, ${state.unknown.length} still learning` : ''} out of ${plural(total, 'card')}.`}
|
||||
</p>
|
||||
<div className="mt-6 flex flex-wrap justify-center gap-2">
|
||||
{state.unknown.length > 0 && (
|
||||
|
|
|
|||
|
|
@ -1,5 +1,8 @@
|
|||
import { useEffect, useSyncExternalStore } from 'react';
|
||||
|
||||
/** Drag-and-drop payload for library items: set by class pages, read by the assistant panel. */
|
||||
export const ITEM_DRAG_TYPE = 'application/x-studydesk-item';
|
||||
|
||||
export interface AssistantSeed {
|
||||
id: number;
|
||||
prompt?: string;
|
||||
|
|
|
|||
|
|
@ -76,6 +76,12 @@ export interface DueCounts {
|
|||
total: number;
|
||||
}
|
||||
|
||||
/** AI features a share link's visitors may use. */
|
||||
export interface ShareAi {
|
||||
explain: boolean;
|
||||
assistant: boolean;
|
||||
}
|
||||
|
||||
export interface Share {
|
||||
id: string;
|
||||
token: string;
|
||||
|
|
@ -83,6 +89,7 @@ export interface Share {
|
|||
viewCount: number;
|
||||
lastViewedAt: number | null;
|
||||
createdAt: number;
|
||||
ai?: ShareAi;
|
||||
}
|
||||
|
||||
export interface ClassDetail {
|
||||
|
|
@ -469,10 +476,13 @@ export interface Mentionable extends TaggedItem {
|
|||
classColor: string;
|
||||
folderName?: string;
|
||||
}
|
||||
export type MessagePart = { kind: 'text'; text: string } | { kind: 'tool'; id: string } | { kind: 'ui'; index: number };
|
||||
export interface ChatMessage {
|
||||
id: number | string;
|
||||
role: 'user' | 'assistant';
|
||||
text: string;
|
||||
/** Text, tool steps and cards in the order they happened. */
|
||||
parts?: MessagePart[];
|
||||
tags?: TaggedItem[];
|
||||
tools: ToolActivity[];
|
||||
ui: UiItem[];
|
||||
|
|
@ -485,6 +495,7 @@ export interface ChatMessage {
|
|||
export type AssistantEvent =
|
||||
| { type: 'start'; conversationId: string; model: string }
|
||||
| { type: 'text'; delta: string }
|
||||
| { type: 'step' }
|
||||
| { type: 'reasoning'; delta: string }
|
||||
| { type: 'tool'; tool: ToolActivity }
|
||||
| { type: 'ui'; item: UiItem }
|
||||
|
|
@ -544,4 +555,4 @@ export interface PublicCollection {
|
|||
folders: { id: string; name: string }[];
|
||||
items: { kind: 'quiz' | 'deck' | 'note' | 'document'; id: string; title: string; description: string; folderId: string | null; count: number }[];
|
||||
}
|
||||
export type PublicPayload = PublicQuiz | PublicDeck | PublicNote | PublicDocument | PublicCollection;
|
||||
export type PublicPayload = (PublicQuiz | PublicDeck | PublicNote | PublicDocument | PublicCollection) & { ai?: ShareAi };
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ import { GenerateDialog, type GeneratePreset } from '@/features/GenerateDialog';
|
|||
import { ImportDialog } from '@/features/ImportDialog';
|
||||
import { useStartSession } from '@/features/study';
|
||||
import { api, errorMessage, uploadWithProgress } from '@/lib/api';
|
||||
import { assistant, useAssistantContext } from '@/lib/assistantStore';
|
||||
import { assistant, ITEM_DRAG_TYPE, useAssistantContext } from '@/lib/assistantStore';
|
||||
import { useClass, useRefresh } from '@/lib/queries';
|
||||
import type { DeckItem, DocumentItem, Folder, Item, NoteItem, QuizItem } from '@/lib/types';
|
||||
import { cx, downloadFile, formatBytes, gradeTone, plural, timeAgo, useDocumentTitle, useLocalStorage } from '@/lib/util';
|
||||
|
|
@ -276,7 +276,15 @@ export default function ClassPage() {
|
|||
{sortable?.handle}
|
||||
<KindIcon item={item} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<Link to={`/${ITEM_URL[item.kind]}/${item.id}`} className="block truncate text-[15px] font-medium text-ink after:absolute after:inset-0">
|
||||
<Link
|
||||
to={`/${ITEM_URL[item.kind]}/${item.id}`}
|
||||
className="block truncate text-[15px] font-medium text-ink after:absolute after:inset-0"
|
||||
onDragStart={(e) => {
|
||||
// Dropping this onto the assistant adds it to the chat.
|
||||
e.dataTransfer.setData(ITEM_DRAG_TYPE, JSON.stringify({ kind: item.kind, id: item.id, title: item.title }));
|
||||
e.dataTransfer.effectAllowed = 'copyLink';
|
||||
}}
|
||||
>
|
||||
{item.title}
|
||||
</Link>
|
||||
<div className="mt-0.5 flex items-center gap-x-2.5 overflow-hidden text-xs whitespace-nowrap text-ink-3">
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router';
|
||||
import { useNavigate, useParams, useSearchParams } from 'react-router';
|
||||
import { Explain } from '@/features/Explain';
|
||||
import { CramSession, freshCramState, reconcileCramState, type CramState } from '@/features/flashcards';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
|
|
@ -7,23 +7,33 @@ import { useAiStatus, useDeck, useRefresh } from '@/lib/queries';
|
|||
import { useDocumentTitle } from '@/lib/util';
|
||||
import { Button, EmptyState, ErrorState, PageLoading } from '@/ui';
|
||||
|
||||
/** Browse every card in a deck, self-graded. Does not affect the spaced-repetition schedule. */
|
||||
/** Standard study: every card in a deck, self-graded. Does not affect the spaced-repetition schedule. */
|
||||
export default function CramPage() {
|
||||
const { deckId = '' } = useParams();
|
||||
const [params, setParams] = useSearchParams();
|
||||
const navigate = useNavigate();
|
||||
const refresh = useRefresh();
|
||||
const ai = useAiStatus();
|
||||
const q = useDeck(deckId);
|
||||
const data = q.data;
|
||||
useDocumentTitle(data ? `Browse · ${data.deck.title}` : undefined);
|
||||
useDocumentTitle(data ? `Study · ${data.deck.title}` : undefined);
|
||||
const [state, setState] = useState<CramState | null>(null);
|
||||
const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const latest = useRef<CramState | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!data || state) return;
|
||||
// ?new=1 starts a fresh session with the options chosen on the deck page; otherwise resume.
|
||||
if (params.get('new')) {
|
||||
const next = freshCramState(data.cards, params.get('shuffle') === '1', 1, params.get('repeat') === '1');
|
||||
setState(next);
|
||||
latest.current = next;
|
||||
void api.put(`/api/decks/${deckId}/session`, { state: next }).catch(() => undefined);
|
||||
setParams({}, { replace: true });
|
||||
return;
|
||||
}
|
||||
setState(reconcileCramState(data.session?.state as CramState | null, data.cards) ?? freshCramState(data.cards, false));
|
||||
}, [data, state]);
|
||||
}, [data, state, params, setParams, deckId]);
|
||||
|
||||
const persist = (next: CramState) => {
|
||||
setState(next);
|
||||
|
|
|
|||
|
|
@ -9,10 +9,10 @@ import { GenerateDialog, type GeneratePreset } from '@/features/GenerateDialog';
|
|||
import { api, errorMessage } from '@/lib/api';
|
||||
import { useAssistantContext } from '@/lib/assistantStore';
|
||||
import { useAiStatus, useDeck, useRefresh } from '@/lib/queries';
|
||||
import { cx, downloadFile, plural, useDocumentTitle } from '@/lib/util';
|
||||
import { cx, downloadFile, plural, useDocumentTitle, useLocalStorage } from '@/lib/util';
|
||||
import { Markdown } from '@/ui/Markdown';
|
||||
import { SortableList } from '@/ui/Sortable';
|
||||
import { Badge, Button, ClassDot, EmptyState, ErrorState, IconButton, Input, Menu, MenuItem, MenuSeparator, Skeleton, Tooltip, useConfirm } from '@/ui';
|
||||
import { Badge, Button, Callout, ClassDot, EmptyState, ErrorState, IconButton, Input, Menu, MenuItem, MenuSeparator, Skeleton, Switch, Tooltip, useConfirm } from '@/ui';
|
||||
import { BulkAddDialog } from './QuizPage';
|
||||
|
||||
function dueLabel(card: Card): { text: string; tone: 'neutral' | 'accent' | 'good' | 'warn' } {
|
||||
|
|
@ -24,6 +24,87 @@ function dueLabel(card: Card): { text: string; tone: 'neutral' | 'accent' | 'goo
|
|||
return { text: days === 1 ? 'Tomorrow' : days < 31 ? `${days} days` : days < 365 ? `${Math.round(days / 30)} mo` : `${(days / 365).toFixed(1)} y`, tone: 'good' };
|
||||
}
|
||||
|
||||
interface DeckStudyPrefs {
|
||||
mode: 'standard' | 'srs';
|
||||
/** Standard mode: missed cards come round again until they are known. */
|
||||
repeatMissed: boolean;
|
||||
shuffle: boolean;
|
||||
}
|
||||
|
||||
/** Pick how to study the deck: a standard pass (know it / still learning) or spaced repetition. */
|
||||
function StudyPanel({ deckId, cardCount, due, hasSession }: { deckId: string; cardCount: number; due: number; hasSession: boolean }) {
|
||||
const navigate = useNavigate();
|
||||
const [prefs, setPrefs] = useLocalStorage<DeckStudyPrefs>('sd.deckStudyPrefs', { mode: 'standard', repeatMissed: true, shuffle: true });
|
||||
if (cardCount === 0) return null;
|
||||
const srs = prefs.mode === 'srs';
|
||||
const start = () => navigate(srs ? `/review?deckId=${deckId}` : `/decks/${deckId}/cram?new=1&repeat=${prefs.repeatMissed ? 1 : 0}&shuffle=${prefs.shuffle ? 1 : 0}`);
|
||||
return (
|
||||
<section className="card mb-6 p-5 sm:p-6" aria-label="Study this deck">
|
||||
{hasSession && !srs && (
|
||||
<Callout
|
||||
tone="warn"
|
||||
icon={<Play />}
|
||||
className="mb-5"
|
||||
title="You have a session in progress"
|
||||
action={
|
||||
<Button to={`/decks/${deckId}/cram`} variant="marker" size="sm">
|
||||
Resume
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
Pick up where you left off, or start a new one below.
|
||||
</Callout>
|
||||
)}
|
||||
<div className="grid grid-cols-2 gap-2" role="radiogroup" aria-label="Study mode">
|
||||
{(
|
||||
[
|
||||
{ v: 'standard', title: 'Standard', body: 'Go through the cards and mark each one known or still learning. Your review schedule is not changed.' },
|
||||
{ v: 'srs', title: 'Spaced repetition', body: 'Review the cards that are due. How well you remember each one sets when it comes back.' },
|
||||
] as const
|
||||
).map((m) => (
|
||||
<button
|
||||
key={m.v}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={prefs.mode === m.v}
|
||||
onClick={() => setPrefs((p) => ({ ...p, mode: m.v }))}
|
||||
className={cx('rounded-xl border p-3.5 text-left transition-colors', prefs.mode === m.v ? 'border-accent bg-accent-soft' : 'border-line-strong hover:border-ink-3')}
|
||||
>
|
||||
<div className="font-semibold">{m.title}</div>
|
||||
<div className="mt-1 text-[13px] leading-snug text-ink-2">{m.body}</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{srs ? (
|
||||
<p className="mt-4 text-[13px] text-ink-2">
|
||||
{due > 0 ? (
|
||||
<>
|
||||
<strong className="marker num text-ink">{due}</strong> {due === 1 ? 'card is' : 'cards are'} due now, including new cards for today.
|
||||
</>
|
||||
) : (
|
||||
'Nothing is due right now. Cards come back when they are due; use Standard to go through them any time.'
|
||||
)}
|
||||
</p>
|
||||
) : (
|
||||
<div className="mt-4 space-y-4 rounded-xl border border-line p-4">
|
||||
<Switch
|
||||
checked={prefs.repeatMissed}
|
||||
onChange={(v) => setPrefs((p) => ({ ...p, repeatMissed: v }))}
|
||||
label="Repeat missed cards until I know them"
|
||||
description={prefs.repeatMissed ? 'A card you miss goes to the back of the pile and comes round again.' : 'Go through the deck once, then choose whether to study the missed cards.'}
|
||||
/>
|
||||
<Switch checked={prefs.shuffle} onChange={(v) => setPrefs((p) => ({ ...p, shuffle: v }))} label="Shuffle cards" />
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-5 flex flex-wrap items-center gap-2 border-t border-line pt-5">
|
||||
<Button variant="primary" size="lg" icon={<Play className="fill-current" />} onClick={start} disabled={srs && due === 0} className="min-w-40">
|
||||
{srs ? (due > 0 ? `Review ${due}` : 'Nothing due') : hasSession ? 'Start new session' : 'Start'}
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export default function DeckPage() {
|
||||
const { deckId = '' } = useParams();
|
||||
const [params, setParams] = useSearchParams();
|
||||
|
|
@ -123,7 +204,6 @@ export default function DeckPage() {
|
|||
{ label: 'Young', n: stats.young, cls: 'bg-good/55' },
|
||||
{ label: 'Mature', n: stats.mature, cls: 'bg-good' },
|
||||
];
|
||||
const canStudy = due.total > 0;
|
||||
|
||||
return (
|
||||
<div className={cx('animate-in', `tab-${data.class.color}`)}>
|
||||
|
|
@ -155,12 +235,6 @@ export default function DeckPage() {
|
|||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button to={`/review?deckId=${deck.id}`} variant={canStudy ? 'primary' : 'secondary'} size="lg" icon={<Play className="fill-current" />} disabled={!canStudy}>
|
||||
{canStudy ? `Review ${due.total}` : 'Nothing due'}
|
||||
</Button>
|
||||
<Button to={`/decks/${deck.id}/cram`} size="lg" icon={<Layers />} disabled={cards.length === 0}>
|
||||
{data.session ? 'Continue browsing' : 'Browse all'}
|
||||
</Button>
|
||||
<Menu
|
||||
trigger={
|
||||
<IconButton label="Deck options" tooltip={false}>
|
||||
|
|
@ -215,6 +289,8 @@ export default function DeckPage() {
|
|||
</div>
|
||||
</header>
|
||||
|
||||
<StudyPanel deckId={deck.id} cardCount={cards.length} due={due.total} hasSession={Boolean(data.session)} />
|
||||
|
||||
{stats.total > 0 && (
|
||||
<div className="card mb-6 p-4">
|
||||
<div className="flex h-2.5 overflow-hidden rounded-full bg-ink/8" role="img" aria-label={segments.map((s) => `${s.n} ${s.label.toLowerCase()}`).join(', ')}>
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
|
||||
import { BookOpen, ChevronRight, Download, FileText, FolderInput, Layers, MessageSquare, MoreHorizontal, NotebookPen, Pencil, RefreshCw, ScanText, Share2, Sparkles, Trash2, TriangleAlert } from 'lucide-react';
|
||||
import { BookOpen, ChevronRight, Columns2, Download, FileText, FolderInput, Layers, MessageSquare, MoreHorizontal, NotebookPen, Pencil, RefreshCw, ScanText, Share2, Sparkles, Trash2, TriangleAlert } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link, useNavigate, useParams, useSearchParams } from 'react-router';
|
||||
import { toast } from 'sonner';
|
||||
|
|
@ -9,7 +9,7 @@ import { api, errorMessage } from '@/lib/api';
|
|||
import { assistant, useAssistantContext } from '@/lib/assistantStore';
|
||||
import { qk, useAiStatus, useRefresh } from '@/lib/queries';
|
||||
import type { ClassInfo, DocChunk, DocumentInfo, Share } from '@/lib/types';
|
||||
import { cx, downloadFile, formatBytes, formatTokens, plural, useDocumentTitle } from '@/lib/util';
|
||||
import { cx, downloadFile, formatBytes, formatTokens, plural, useDocumentTitle, useLocalStorage } from '@/lib/util';
|
||||
import { Markdown } from '@/ui/Markdown';
|
||||
import { Badge, Button, Callout, ClassDot, EmptyState, ErrorState, IconButton, Menu, MenuItem, MenuSeparator, ProgressBar, Segmented, Skeleton, Spinner, useConfirm } from '@/ui';
|
||||
|
||||
|
|
@ -36,7 +36,7 @@ export default function DocumentPage() {
|
|||
const refresh = useRefresh();
|
||||
const confirm = useConfirm();
|
||||
const ai = useAiStatus();
|
||||
const [view, setView] = useState<'text' | 'original'>('text');
|
||||
const [view, setView] = useLocalStorage<'text' | 'side' | 'original'>('sd.documentView', 'text');
|
||||
const [rename, setRename] = useState(false);
|
||||
const [move, setMove] = useState(false);
|
||||
const [share, setShare] = useState(false);
|
||||
|
|
@ -77,7 +77,7 @@ export default function DocumentPage() {
|
|||
}
|
||||
const cls = q.data.class;
|
||||
const busy = doc.status === 'pending' || doc.status === 'processing';
|
||||
const hasOriginal = doc.docKind === 'pdf' || doc.docKind === 'image';
|
||||
const hasOriginal = doc.docKind === 'pdf' || doc.docKind === 'image' || doc.docKind === 'docx' || doc.docKind === 'pptx';
|
||||
const fileUrl = `/api/documents/${doc.id}/file`;
|
||||
|
||||
const reprocess = async (ocr: boolean) => {
|
||||
|
|
@ -99,6 +99,65 @@ export default function DocumentPage() {
|
|||
}
|
||||
};
|
||||
const all = chunks.data?.pages.flatMap((p) => p.chunks) ?? [];
|
||||
const office = doc.docKind === 'docx' || doc.docKind === 'pptx';
|
||||
const originalView = (height: string) =>
|
||||
doc.docKind === 'image' ? (
|
||||
<div className="card grid place-items-center p-4">
|
||||
<img src={fileUrl} alt={doc.title} className="max-h-[80vh] max-w-full rounded-lg" />
|
||||
</div>
|
||||
) : (
|
||||
// Office previews are self-contained HTML; the server sandboxes them with its Content-Security-Policy.
|
||||
<iframe src={office ? `/api/documents/${doc.id}/preview` : fileUrl} title={`${doc.title} (original)`} className={cx('card w-full bg-surface', height)} />
|
||||
);
|
||||
const noText = !ready ? null : doc.chunkCount === 0 ? (
|
||||
<div className="card">
|
||||
<EmptyState icon={<FileText />} title="No text to show">
|
||||
{doc.needsOcr ? 'Use "Read with AI" above to transcribe this file.' : 'Nothing readable was found in this file.'}
|
||||
</EmptyState>
|
||||
</div>
|
||||
) : null;
|
||||
const articleView = (
|
||||
<div className="min-w-0">
|
||||
{firstOffset > 0 && <div className="mb-3 rounded-xl border border-dashed border-line-strong px-4 py-2.5 text-[13px] text-ink-3">Showing from section {firstOffset + 1}. <Link to={`/documents/${doc.id}`} className="font-medium text-accent hover:underline">Start from the beginning</Link></div>}
|
||||
<article className="card divide-y divide-line">
|
||||
{chunks.isLoading && (
|
||||
<div className="space-y-3 p-6">
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
<Skeleton className="h-4" />
|
||||
<Skeleton className="h-4 w-5/6" />
|
||||
</div>
|
||||
)}
|
||||
{all.map((ch, i) => {
|
||||
const prev = all[i - 1];
|
||||
const showHeading = ch.heading && ch.heading !== prev?.heading;
|
||||
const showPage = ch.pageStart !== null && ch.pageStart !== prev?.pageStart;
|
||||
return (
|
||||
<section key={ch.id} id={`chunk-${ch.id}`} className={cx('scroll-mt-24 px-5 py-4 sm:px-8', focusChunk === ch.id && 'bg-marker/25')}>
|
||||
{(showHeading || showPage) && (
|
||||
<div className="mb-2 flex flex-wrap items-baseline justify-between gap-2">
|
||||
{showHeading ? <h2 className="display text-[19px]">{ch.heading}</h2> : <span />}
|
||||
{showPage && (
|
||||
<span className="num text-[11px] text-ink-3">
|
||||
{doc.docKind === 'pptx' ? 'Slide' : 'Page'} {ch.pageStart}
|
||||
{ch.pageEnd && ch.pageEnd !== ch.pageStart ? `–${ch.pageEnd}` : ''}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<Markdown className="text-[15px] text-ink">{ch.text}</Markdown>
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
</article>
|
||||
{chunks.hasNextPage && (
|
||||
<div className="mt-4 flex justify-center">
|
||||
<Button loading={chunks.isFetchingNextPage} onClick={() => chunks.fetchNextPage()}>
|
||||
Show more
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={cx('animate-in', `tab-${cls.color}`)}>
|
||||
|
|
@ -239,6 +298,7 @@ export default function DocumentPage() {
|
|||
onChange={setView}
|
||||
options={[
|
||||
{ value: 'text', label: 'Extracted text', icon: <FileText /> },
|
||||
{ value: 'side', label: 'Side by side', icon: <Columns2 /> },
|
||||
{ value: 'original', label: 'Original', icon: <ScanText /> },
|
||||
]}
|
||||
/>
|
||||
|
|
@ -246,94 +306,50 @@ export default function DocumentPage() {
|
|||
)}
|
||||
|
||||
{view === 'original' && hasOriginal ? (
|
||||
doc.docKind === 'image' ? (
|
||||
<div className="card grid place-items-center p-4">
|
||||
<img src={fileUrl} alt={doc.title} className="max-h-[80vh] max-w-full rounded-lg" />
|
||||
</div>
|
||||
) : (
|
||||
<iframe src={fileUrl} title={doc.title} className="card h-[82vh] w-full" />
|
||||
)
|
||||
) : !ready ? null : doc.chunkCount === 0 ? (
|
||||
<div className="card">
|
||||
<EmptyState icon={<FileText />} title="No text to show">
|
||||
{doc.needsOcr ? 'Use "Read with AI" above to transcribe this file.' : 'Nothing readable was found in this file.'}
|
||||
</EmptyState>
|
||||
originalView('h-[82vh]')
|
||||
) : view === 'side' && hasOriginal ? (
|
||||
<div className="grid items-start gap-4 lg:grid-cols-2">
|
||||
<div className="lg:sticky lg:top-4">{originalView('h-[60vh] lg:h-[calc(100dvh-2rem)]')}</div>
|
||||
<div className="min-w-0">{ready ? (noText ?? articleView) : null}</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-6 lg:grid-cols-[1fr_220px]">
|
||||
<div className="min-w-0">
|
||||
{firstOffset > 0 && <div className="mb-3 rounded-xl border border-dashed border-line-strong px-4 py-2.5 text-[13px] text-ink-3">Showing from section {firstOffset + 1}. <Link to={`/documents/${doc.id}`} className="font-medium text-accent hover:underline">Start from the beginning</Link></div>}
|
||||
<article className="card divide-y divide-line">
|
||||
{chunks.isLoading && (
|
||||
<div className="space-y-3 p-6">
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
<Skeleton className="h-4" />
|
||||
<Skeleton className="h-4 w-5/6" />
|
||||
) : !ready ? null : (
|
||||
noText ?? (
|
||||
<div className="grid gap-6 lg:grid-cols-[1fr_220px]">
|
||||
{articleView}
|
||||
{q.data.outline.length > 1 && (
|
||||
<aside className="hidden lg:block">
|
||||
<div className="sticky top-8">
|
||||
<div className="eyebrow mb-2">Outline</div>
|
||||
<ul className="max-h-[70vh] space-y-0.5 overflow-y-auto text-[13px]">
|
||||
{q.data.outline.map((o) => (
|
||||
<li key={o.seq}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={async () => {
|
||||
// Load forward until the section is on the page, then scroll to it.
|
||||
let pages = chunks.data?.pages ?? [];
|
||||
let guard = 0;
|
||||
while (!pages.some((p) => p.chunks.some((c) => c.seq === o.seq)) && pages[pages.length - 1]?.nextOffset !== null && guard < 40) {
|
||||
const res = await chunks.fetchNextPage();
|
||||
pages = res.data?.pages ?? [];
|
||||
guard += 1;
|
||||
}
|
||||
const hit = pages.flatMap((p) => p.chunks).find((c) => c.seq === o.seq);
|
||||
if (hit) document.getElementById(`chunk-${hit.id}`)?.scrollIntoView({ block: 'start', behavior: 'smooth' });
|
||||
}}
|
||||
className="block w-full truncate rounded-md px-2 py-1 text-left text-ink-2 hover:bg-ink/5 hover:text-ink"
|
||||
title={o.heading}
|
||||
>
|
||||
{o.heading}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
{all.map((ch, i) => {
|
||||
const prev = all[i - 1];
|
||||
const showHeading = ch.heading && ch.heading !== prev?.heading;
|
||||
const showPage = ch.pageStart !== null && ch.pageStart !== prev?.pageStart;
|
||||
return (
|
||||
<section key={ch.id} id={`chunk-${ch.id}`} className={cx('scroll-mt-24 px-5 py-4 sm:px-8', focusChunk === ch.id && 'bg-marker/25')}>
|
||||
{(showHeading || showPage) && (
|
||||
<div className="mb-2 flex flex-wrap items-baseline justify-between gap-2">
|
||||
{showHeading ? <h2 className="display text-[19px]">{ch.heading}</h2> : <span />}
|
||||
{showPage && (
|
||||
<span className="num text-[11px] text-ink-3">
|
||||
{doc.docKind === 'pptx' ? 'Slide' : 'Page'} {ch.pageStart}
|
||||
{ch.pageEnd && ch.pageEnd !== ch.pageStart ? `–${ch.pageEnd}` : ''}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<Markdown className="text-[15px] text-ink">{ch.text}</Markdown>
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
</article>
|
||||
{chunks.hasNextPage && (
|
||||
<div className="mt-4 flex justify-center">
|
||||
<Button loading={chunks.isFetchingNextPage} onClick={() => chunks.fetchNextPage()}>
|
||||
Show more
|
||||
</Button>
|
||||
</div>
|
||||
</aside>
|
||||
)}
|
||||
</div>
|
||||
{q.data.outline.length > 1 && (
|
||||
<aside className="hidden lg:block">
|
||||
<div className="sticky top-8">
|
||||
<div className="eyebrow mb-2">Outline</div>
|
||||
<ul className="max-h-[70vh] space-y-0.5 overflow-y-auto text-[13px]">
|
||||
{q.data.outline.map((o) => (
|
||||
<li key={o.seq}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={async () => {
|
||||
// Load forward until the section is on the page, then scroll to it.
|
||||
let pages = chunks.data?.pages ?? [];
|
||||
let guard = 0;
|
||||
while (!pages.some((p) => p.chunks.some((c) => c.seq === o.seq)) && pages[pages.length - 1]?.nextOffset !== null && guard < 40) {
|
||||
const res = await chunks.fetchNextPage();
|
||||
pages = res.data?.pages ?? [];
|
||||
guard += 1;
|
||||
}
|
||||
const hit = pages.flatMap((p) => p.chunks).find((c) => c.seq === o.seq);
|
||||
if (hit) document.getElementById(`chunk-${hit.id}`)?.scrollIntoView({ block: 'start', behavior: 'smooth' });
|
||||
}}
|
||||
className="block w-full truncate rounded-md px-2 py-1 text-left text-ink-2 hover:bg-ink/5 hover:text-ink"
|
||||
title={o.heading}
|
||||
>
|
||||
{o.heading}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</aside>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
|
||||
<RenameDialog target={rename ? { kind: 'document', id: doc.id, title: doc.title } : null} onClose={() => setRename(false)} />
|
||||
|
|
|
|||
|
|
@ -154,9 +154,6 @@ function StartPanel({ quizId, total, resume, onShowQuestions }: { quizId: string
|
|||
<Button variant="primary" size="lg" icon={<Play className="fill-current" />} loading={o.starting} onClick={o.go} className="min-w-40">
|
||||
{resume ? 'Start new session' : 'Start'}
|
||||
</Button>
|
||||
<Button variant="ghost" size="lg" icon={<ClipboardList />} onClick={onShowQuestions} className="ml-auto">
|
||||
View questions and answers
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -3,7 +3,9 @@ import { ArrowLeft, BookOpen, ChevronRight, Download, FileText, Layers, Link2Off
|
|||
import { useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||
import { Link, useNavigate, useParams } from 'react-router';
|
||||
import { isFullyCorrect, scoreQuestion, seededShuffle } from '@shared/content';
|
||||
import { Explain } from '@/features/Explain';
|
||||
import { CramSession, freshCramState, reconcileCramState, type CramState } from '@/features/flashcards';
|
||||
import { SharedAssistant } from '@/features/SharedAssistant';
|
||||
import { QuizResults, QuizRunner } from '@/features/quiz';
|
||||
import { api, ApiError } from '@/lib/api';
|
||||
import type { AnswerState, PublicCollection, PublicDeck, PublicDocument, PublicNote, PublicPayload, PublicQuiz, SnapshotQuestion } from '@/lib/types';
|
||||
|
|
@ -116,7 +118,8 @@ function buildQuizState(quiz: PublicQuiz, mode: QuizState['mode'], shuffleQ: boo
|
|||
};
|
||||
}
|
||||
|
||||
function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey: string; back?: { to: string; label: string } }) {
|
||||
function SharedQuiz({ quiz, storageKey, back, explainUrl }: { quiz: PublicQuiz; storageKey: string; back?: { to: string; label: string }; explainUrl?: string }) {
|
||||
const renderExtra = explainUrl ? (q: SnapshotQuestion, selected: string[]) => <Explain url={explainUrl} body={{ kind: 'question', quizId: quiz.id, questionId: q.id, selected }} /> : undefined;
|
||||
const [state, setState] = useLocalStorage<QuizState | null>(storageKey, null);
|
||||
const [prefs, setPrefs] = useLocalStorage('sd.pub.prefs2', { mode: 'practice' as 'practice' | 'exam', shuffleQ: true, shuffleO: true, timed: false, minutes: 0 });
|
||||
const minutes = prefs.minutes > 0 ? prefs.minutes : Math.max(5, Math.round(quiz.questions.length * 1.2));
|
||||
|
|
@ -169,6 +172,7 @@ function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey:
|
|||
onExit={() => (setState(null), setRunning(false))}
|
||||
exitLabel="Back to start"
|
||||
footnote="This result is stored in your browser only. The person who shared the quiz cannot see it."
|
||||
renderExtra={renderExtra}
|
||||
actions={
|
||||
<>
|
||||
{missed.length > 0 && (
|
||||
|
|
@ -199,6 +203,7 @@ function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey:
|
|||
deadlineAt={state.deadlineAt ?? null}
|
||||
sataScoring="partial"
|
||||
exitLabel={state.deadlineAt ? 'Leave (the clock keeps running)' : 'Pause'}
|
||||
renderExtra={renderExtra}
|
||||
onAnswer={(qid, selected, checked) => setState((s) => (s ? { ...s, answers: { ...s.answers, [qid]: { selected, checked } } } : s))}
|
||||
onFlags={(flags) => setState((s) => (s ? { ...s, flags } : s))}
|
||||
onIndex={(index) => setState((s) => (s ? { ...s, index } : s))}
|
||||
|
|
@ -283,13 +288,24 @@ function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey:
|
|||
|
||||
/* ------------------------------ deck ------------------------------ */
|
||||
|
||||
function SharedDeck({ deck, storageKey, back }: { deck: PublicDeck; storageKey: string; back?: { to: string; label: string } }) {
|
||||
function SharedDeck({ deck, storageKey, back, explainUrl }: { deck: PublicDeck; storageKey: string; back?: { to: string; label: string }; explainUrl?: string }) {
|
||||
const [saved, setSaved] = useLocalStorage<CramState | null>(storageKey, null);
|
||||
const [running, setRunning] = useState(false);
|
||||
const state = useMemo(() => reconcileCramState(saved, deck.cards), [saved, deck.cards]);
|
||||
|
||||
if (running && state) {
|
||||
return <CramSession title={deck.title} subtitle="Shared flashcards" cards={deck.cards} state={state} onState={setSaved} onExit={() => setRunning(false)} exitLabel="Pause" />;
|
||||
return (
|
||||
<CramSession
|
||||
title={deck.title}
|
||||
subtitle="Shared flashcards"
|
||||
cards={deck.cards}
|
||||
state={state}
|
||||
onState={setSaved}
|
||||
onExit={() => setRunning(false)}
|
||||
exitLabel="Pause"
|
||||
renderExtra={explainUrl ? (card) => <Explain url={explainUrl} body={{ kind: 'card', deckId: deck.id, cardId: card.id }} /> : undefined}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const seen = state ? Math.min(state.index, state.order.length) : 0;
|
||||
return (
|
||||
|
|
@ -456,16 +472,26 @@ export default function SharedPage() {
|
|||
}
|
||||
const back = nested ? { to: `/s/${token}`, label: 'All materials' } : undefined;
|
||||
const key = `sd.pub.${token.slice(0, 12)}.${data.kind}.${'id' in data ? data.id : ''}`;
|
||||
switch (data.kind) {
|
||||
case 'quiz':
|
||||
return <SharedQuiz key={key} quiz={data} storageKey={key} back={back} />;
|
||||
case 'deck':
|
||||
return <SharedDeck key={key} deck={data} storageKey={key} back={back} />;
|
||||
case 'note':
|
||||
return <SharedNote note={data} back={back} />;
|
||||
case 'document':
|
||||
return <SharedDocument doc={data} token={token} nested={nested} back={back} />;
|
||||
case 'collection':
|
||||
return <SharedCollection data={data} token={token} />;
|
||||
}
|
||||
const explainUrl = data.ai?.explain ? `/api/public/${token}/explain` : undefined;
|
||||
const assistant = data.ai?.assistant ? <SharedAssistant token={token} title={data.title} item={nested && data.kind !== 'collection' ? { kind: data.kind, id: data.id } : undefined} /> : null;
|
||||
const page = (() => {
|
||||
switch (data.kind) {
|
||||
case 'quiz':
|
||||
return <SharedQuiz key={key} quiz={data} storageKey={key} back={back} explainUrl={explainUrl} />;
|
||||
case 'deck':
|
||||
return <SharedDeck key={key} deck={data} storageKey={key} back={back} explainUrl={explainUrl} />;
|
||||
case 'note':
|
||||
return <SharedNote note={data} back={back} />;
|
||||
case 'document':
|
||||
return <SharedDocument doc={data} token={token} nested={nested} back={back} />;
|
||||
case 'collection':
|
||||
return <SharedCollection data={data} token={token} />;
|
||||
}
|
||||
})();
|
||||
return (
|
||||
<>
|
||||
{page}
|
||||
{assistant}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -456,38 +456,54 @@
|
|||
}
|
||||
}
|
||||
|
||||
/* Streak flames. The yellow-to-orange ramp is the same in both themes on purpose. */
|
||||
/* Streaks, in the app's own palette: accent ink with a highlighter (marker) sheen. */
|
||||
.streak-bar {
|
||||
background-image: linear-gradient(100deg, #fbbf24, #fb923c 35%, #ea580c 55%, #fb923c 75%, #fbbf24);
|
||||
background-size: 200% 100%;
|
||||
animation: sd-flame-flow 2.6s linear infinite;
|
||||
box-shadow: 0 0 12px rgb(234 88 12 / 0.5);
|
||||
background-color: var(--accent);
|
||||
background-image: linear-gradient(100deg, transparent 0 38%, color-mix(in srgb, var(--marker) 85%, transparent) 50%, transparent 62% 100%);
|
||||
background-size: 260% 100%;
|
||||
animation: sd-flame-flow 2.4s linear infinite;
|
||||
}
|
||||
.streak-chip {
|
||||
animation: sd-pop 280ms cubic-bezier(0.2, 0.9, 0.3, 1.3);
|
||||
}
|
||||
.streak-chip-hot {
|
||||
color: #451a03;
|
||||
background-image: linear-gradient(100deg, #fbbf24, #ea580c);
|
||||
box-shadow: 0 2px 12px rgb(234 88 12 / 0.4);
|
||||
color: var(--marker-ink);
|
||||
background: var(--marker);
|
||||
}
|
||||
.streak-scrim {
|
||||
background: radial-gradient(circle at 50% 46%, color-mix(in srgb, var(--surface) 94%, transparent) 0%, color-mix(in srgb, var(--surface) 78%, transparent) 42%, transparent 76%);
|
||||
background: radial-gradient(circle at 50% 46%, var(--surface) 0%, var(--surface) 34%, color-mix(in srgb, var(--surface) 88%, transparent) 52%, transparent 80%);
|
||||
animation: sd-streak-scrim var(--streak-ms, 1800ms) ease-out forwards;
|
||||
}
|
||||
.streak-pop {
|
||||
animation: sd-streak-pop var(--streak-ms, 1800ms) cubic-bezier(0.2, 0.9, 0.3, 1.2) forwards;
|
||||
animation: sd-streak-pop var(--streak-ms, 1800ms) cubic-bezier(0.2, 0.9, 0.3, 1.1) forwards;
|
||||
}
|
||||
.streak-flame {
|
||||
animation: sd-flicker 0.9s ease-in-out infinite;
|
||||
transform-origin: 50% 85%;
|
||||
filter: drop-shadow(0 6px 22px rgb(234 88 12 / 0.55));
|
||||
}
|
||||
.streak-heading {
|
||||
background-image: linear-gradient(180deg, #fbbf24, #ea580c);
|
||||
-webkit-background-clip: text;
|
||||
background-clip: text;
|
||||
color: transparent;
|
||||
/* A highlighter stroke drawn behind the number. */
|
||||
.streak-mark {
|
||||
--streak-marker: var(--marker);
|
||||
background-image: linear-gradient(var(--streak-marker), var(--streak-marker));
|
||||
background-repeat: no-repeat;
|
||||
background-position: 0 82%;
|
||||
background-size: 0% 46%;
|
||||
border-radius: 4px;
|
||||
animation: sd-streak-mark var(--streak-ms, 1800ms) cubic-bezier(0.3, 0.7, 0.2, 1) forwards;
|
||||
}
|
||||
/* Same softened highlighter as .marker in dark mode, so light text stays readable on it. */
|
||||
:root[data-theme='dark'] .streak-mark {
|
||||
--streak-marker: color-mix(in srgb, var(--marker) 42%, transparent);
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.streak-bar,
|
||||
.streak-flame {
|
||||
animation: none;
|
||||
}
|
||||
.streak-mark {
|
||||
animation: none;
|
||||
background-size: 100% 46%;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -541,6 +557,16 @@
|
|||
transform: translateY(-14px) scale(0.96);
|
||||
}
|
||||
}
|
||||
@keyframes sd-streak-mark {
|
||||
0%,
|
||||
16% {
|
||||
background-size: 0% 46%;
|
||||
}
|
||||
42%,
|
||||
100% {
|
||||
background-size: 100% 46%;
|
||||
}
|
||||
}
|
||||
@keyframes sd-streak-scrim {
|
||||
0% {
|
||||
opacity: 0;
|
||||
|
|
|
|||
|
|
@ -498,7 +498,7 @@ export function Section({ title, action, children, className }: { title: ReactNo
|
|||
return (
|
||||
<section className={cx('mb-8', className)}>
|
||||
<div className="mb-3 flex items-center justify-between gap-3">
|
||||
<h2 className="eyebrow">{title}</h2>
|
||||
<h2 className="eyebrow shrink-0">{title}</h2>
|
||||
{action}
|
||||
</div>
|
||||
{children}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue