First revision: DeepSeek, numeric questions, background assistant, UI fixes
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m2s
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m2s
Providers and pricing - Add a DeepSeek provider: thinking mode with low/high/max effort, reasoning_content replayed between tool steps, cache-hit usage, /models discovery and catalog prices. - Fix "does not support tool calling": a rejected forced tool_choice (DeepSeek thinking mode) now asks for the call in the prompt; only a genuine no-tools 400 is "unsupported". - Seven reasoning-effort levels (Off to Max) mapped per adapter. - Cached-input price per model, cache-write and DeepSeek off-peak aware cost estimates. - Built-in bge-small embedding model (transformers.js) as the semantic search default. Quizzes - Numeric (type-the-answer) questions: units ignored, optional ± tolerance; editor, runner, importer, templates and generation prompts. - Quiz start screen instead of showing answers; navigator ring no longer clipped and key legend removed; clock only for timed exams; 7-point letter grades. Assistant and generation - Assistant turns run on the server independently of the browser, with re-attach and an explicit stop; drafts tray shows generations in progress. - Per-chat model switcher, @-tagging of class materials, full-width assistant page and a smaller assistant button. - Editable generation instructions and built-in presets, separate from the chatbot import instructions. Other - Dialog footer padding, keyboard hints removed, copy buttons work over plain HTTP, class and folder shares include documents. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
ccdad9728b
commit
f0aabe4d5d
63 changed files with 3892 additions and 488 deletions
|
|
@ -1,13 +1,13 @@
|
|||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { ArrowUp, BookOpen, Check, ChevronRight, CircleAlert, FileText, History, Layers, LoaderCircle, NotebookPen, Play, Plus, Sparkles, Square, Trash2, X } from 'lucide-react';
|
||||
import { ArrowUp, AtSign, BookOpen, Check, ChevronDown, ChevronRight, CircleAlert, FileText, Folder, History, Layers, LoaderCircle, NotebookPen, Play, Plus, Sparkles, Square, Trash2, X } from 'lucide-react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
||||
import { Link, useNavigate } from 'react-router';
|
||||
import { toast } from 'sonner';
|
||||
import { api, errorMessage, streamEvents } from '@/lib/api';
|
||||
import { assistant, useAssistantState } from '@/lib/assistantStore';
|
||||
import { useAiStatus, useClasses, useRefresh } from '@/lib/queries';
|
||||
import type { AssistantEvent, ChatMessage, ToolActivity, UiItem } from '@/lib/types';
|
||||
import { cx, plural, timeAgo } from '@/lib/util';
|
||||
import { useAiModels, useAiStatus, useClasses, useRefresh } from '@/lib/queries';
|
||||
import type { AssistantEvent, ChatMessage, Mentionable, 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';
|
||||
|
||||
|
|
@ -16,6 +16,7 @@ interface Conversation {
|
|||
title: string;
|
||||
classId: string | null;
|
||||
updatedAt: number;
|
||||
running?: boolean;
|
||||
}
|
||||
|
||||
const ITEM_URL = { quiz: 'quizzes', deck: 'decks', note: 'notes', document: 'documents', class: 'classes', attempt: 'session' } as const;
|
||||
|
|
@ -172,6 +173,82 @@ function AssistantMessage({ message, onNavigate, onAction }: { message: ChatMess
|
|||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ composer: model picker and @ tags ------------------------------ */
|
||||
|
||||
const TAG_ICON: Record<TagKind, ReactNode> = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen />, document: <FileText />, folder: <Folder /> };
|
||||
const TAG_NOUN: Record<TagKind, string> = { quiz: 'Quiz', deck: 'Flashcards', note: 'Note', document: 'Document', folder: 'Folder' };
|
||||
|
||||
function TagChip({ item, onRemove, inverted }: { item: TaggedItem; onRemove?: () => void; inverted?: boolean }) {
|
||||
return (
|
||||
<span className={cx('inline-flex h-6 max-w-full items-center gap-1 rounded-full pr-2 pl-1.5 text-xs font-medium [&>svg]:size-3 [&>svg]:shrink-0', inverted ? 'bg-paper/15 text-paper' : 'bg-accent-soft text-accent')}>
|
||||
{TAG_ICON[item.kind]}
|
||||
<span className="truncate">{item.title}</span>
|
||||
{onRemove && (
|
||||
<button type="button" aria-label={`Remove ${item.title}`} onClick={onRemove} className="-mr-1 grid size-4 place-items-center rounded-full hover:bg-accent/15">
|
||||
<X className="size-3" />
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** Model chooser for this chat. "Default" follows the Assistant model set in Settings. */
|
||||
function ModelPicker({ value, onChange, defaultLabel }: { value: string; onChange: (id: string) => void; defaultLabel?: string }) {
|
||||
const models = useAiModels();
|
||||
const usable = (models.data ?? []).filter((m) => m.available);
|
||||
const chosen = usable.find((m) => m.id === value);
|
||||
const providers = [...new Set(usable.map((m) => m.providerName))];
|
||||
return (
|
||||
<Menu
|
||||
align="start"
|
||||
trigger={
|
||||
<button type="button" className="flex max-w-full min-w-0 items-center gap-1 rounded-md text-xs text-ink-3 hover:text-ink" aria-label="Choose the model for this chat">
|
||||
<span className="truncate">{chosen ? chosen.label : defaultLabel ? `${defaultLabel}` : 'Default model'}</span>
|
||||
<ChevronDown className="size-3 shrink-0" />
|
||||
</button>
|
||||
}
|
||||
>
|
||||
<MenuLabel>Model for this chat</MenuLabel>
|
||||
<MenuItem onSelect={() => onChange('')} hint={!chosen ? <Check className="size-3.5" /> : undefined}>
|
||||
Default{defaultLabel ? ` · ${defaultLabel}` : ''}
|
||||
</MenuItem>
|
||||
{providers.map((p) => (
|
||||
<div key={p}>
|
||||
<MenuSeparator />
|
||||
<MenuLabel>{p}</MenuLabel>
|
||||
{usable
|
||||
.filter((m) => m.providerName === p)
|
||||
.map((m) => (
|
||||
<MenuItem key={m.id} onSelect={() => onChange(m.id)} hint={m.id === value ? <Check className="size-3.5" /> : !m.capabilities.tools ? 'no tools' : undefined}>
|
||||
{m.label}
|
||||
</MenuItem>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</Menu>
|
||||
);
|
||||
}
|
||||
|
||||
/** Finds an "@query" being typed just before the caret. */
|
||||
function mentionAt(text: string, caret: number): { start: number; query: string } | null {
|
||||
const before = text.slice(0, caret);
|
||||
const m = /(^|\s)@([^\s@]{0,40})$/.exec(before);
|
||||
return m ? { start: caret - m[2].length - 1, query: m[2] } : null;
|
||||
}
|
||||
|
||||
function useMentionables(classId: string | null, query: string, enabled: boolean) {
|
||||
const debounced = useDebounced(query, 150);
|
||||
// Inside a class: load its materials once and filter here. Elsewhere: search by title.
|
||||
const q = useQuery({
|
||||
queryKey: ['ai', 'mentionables', classId ?? '', classId ? '' : debounced],
|
||||
queryFn: () => api.get<{ items: Mentionable[] }>(`/api/ai/mentionables?${new URLSearchParams(classId ? { classId } : { q: debounced })}`).then((r) => r.items),
|
||||
enabled: enabled && (Boolean(classId) || debounced.length >= 1),
|
||||
staleTime: 30_000,
|
||||
});
|
||||
const needle = query.toLowerCase();
|
||||
return (q.data ?? []).filter((i) => !needle || i.title.toLowerCase().includes(needle) || (i.folderName ?? '').toLowerCase().includes(needle)).slice(0, 40);
|
||||
}
|
||||
|
||||
/* ------------------------------ panel ------------------------------ */
|
||||
|
||||
export default function AssistantPanel({
|
||||
|
|
@ -186,56 +263,166 @@ export default function AssistantPanel({
|
|||
onConversationChange?: (id: string | null) => void;
|
||||
}) {
|
||||
const ai = useAiStatus();
|
||||
const models = useAiModels();
|
||||
const classes = useClasses();
|
||||
const refresh = useRefresh();
|
||||
const qc = useQueryClient();
|
||||
const { seed, context } = useAssistantState();
|
||||
const [conversationId, setConversationId] = useState<string | null>(routeConversationId ?? null);
|
||||
const initialConversation = variant === 'page' ? (routeConversationId ?? null) : assistant.drawerConversation;
|
||||
const [conversationId, setConversationId] = useState<string | null>(initialConversation);
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [input, setInput] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [loadingHistory, setLoadingHistory] = useState(false);
|
||||
const [focusDocs, setFocusDocs] = useState<string[]>([]);
|
||||
const abort = useRef<AbortController | null>(null);
|
||||
const [tags, setTags] = useState<TaggedItem[]>([]);
|
||||
const [mention, setMention] = useState<{ start: number; query: string } | null>(null);
|
||||
const [mentionIndex, setMentionIndex] = useState(0);
|
||||
const [modelId, setModelId] = useLocalStorage('sd.assistant.model', '');
|
||||
/** The connection to the running turn. Aborting it only detaches: the turn continues on the server. */
|
||||
const stream = useRef<AbortController | null>(null);
|
||||
const stopRequested = useRef(false);
|
||||
const conversationRef = useRef<string | null>(initialConversation);
|
||||
const scroller = useRef<HTMLDivElement>(null);
|
||||
const inputRef = useRef<HTMLTextAreaElement>(null);
|
||||
const stick = useRef(true);
|
||||
const handledSeed = useRef(0);
|
||||
|
||||
const history = useQuery({ queryKey: ['ai', 'conversations'], queryFn: () => api.get<{ conversations: Conversation[] }>('/api/ai/conversations').then((r) => r.conversations), staleTime: 30_000 });
|
||||
const availableModel = (models.data ?? []).find((m) => m.id === modelId && m.available);
|
||||
const effectiveModelId = availableModel ? modelId : '';
|
||||
|
||||
const load = useCallback(async (id: string) => {
|
||||
setLoadingHistory(true);
|
||||
try {
|
||||
const res = await api.get<{ messages: ChatMessage[] }>(`/api/ai/conversations/${id}`);
|
||||
setMessages(res.messages);
|
||||
const setConversation = useCallback(
|
||||
(id: string | null) => {
|
||||
conversationRef.current = id;
|
||||
setConversationId(id);
|
||||
stick.current = true;
|
||||
} catch {
|
||||
setConversationId(null);
|
||||
setMessages([]);
|
||||
} finally {
|
||||
setLoadingHistory(false);
|
||||
}
|
||||
if (variant === 'drawer') assistant.rememberDrawerConversation(id);
|
||||
},
|
||||
[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 }));
|
||||
}, []);
|
||||
|
||||
/** Follows a turn (new or already running) until it finishes or this panel detaches. */
|
||||
const follow = useCallback(
|
||||
async (pendingId: string, run: (signal: AbortSignal, onEvent: (e: AssistantEvent) => void) => Promise<void>) => {
|
||||
stream.current?.abort();
|
||||
const controller = new AbortController();
|
||||
stream.current = controller;
|
||||
stopRequested.current = false;
|
||||
setBusy(true);
|
||||
let finished = false;
|
||||
let startedId: string | null = null;
|
||||
try {
|
||||
await run(controller.signal, (e) => {
|
||||
if (e.type === 'start') {
|
||||
startedId = e.conversationId;
|
||||
if (stopRequested.current) void api.post(`/api/ai/chat/${e.conversationId}/stop`).catch(() => undefined);
|
||||
if (e.conversationId !== conversationRef.current) {
|
||||
setConversation(e.conversationId);
|
||||
onConversationChange?.(e.conversationId);
|
||||
}
|
||||
}
|
||||
if (e.type === 'done') finished = true;
|
||||
applyEvent(pendingId, e);
|
||||
});
|
||||
} catch (e) {
|
||||
if ((e as Error)?.name !== 'AbortError') setMessages((list) => list.map((m) => (m.id === pendingId ? { ...m, error: errorMessage(e) } : m)));
|
||||
} finally {
|
||||
if (stream.current === controller) {
|
||||
stream.current = null;
|
||||
setBusy(false);
|
||||
}
|
||||
// Detached (left the conversation): leave the turn running and the message as it is.
|
||||
if (finished || !controller.signal.aborted) {
|
||||
setMessages((list) =>
|
||||
list.map((m) =>
|
||||
m.id === pendingId
|
||||
? { ...m, pending: false, tools: m.tools.map((t) => (t.status === 'running' ? { ...t, status: 'error', summary: 'Stopped' } : t)), text: m.text || (m.error || m.ui.length || m.tools.length ? m.text : stopRequested.current ? '*(Stopped.)*' : m.text) }
|
||||
: m,
|
||||
),
|
||||
);
|
||||
void qc.invalidateQueries({ queryKey: ['ai', 'conversations'] });
|
||||
// Tools may have created drafts, classes or sessions.
|
||||
void refresh();
|
||||
}
|
||||
void startedId;
|
||||
}
|
||||
},
|
||||
[applyEvent, onConversationChange, qc, refresh, setConversation],
|
||||
);
|
||||
|
||||
const load = useCallback(
|
||||
async (id: string) => {
|
||||
stream.current?.abort();
|
||||
setLoadingHistory(true);
|
||||
try {
|
||||
const res = await api.get<{ conversation: { id: string; running?: boolean }; messages: ChatMessage[] }>(`/api/ai/conversations/${id}`);
|
||||
setConversation(id);
|
||||
stick.current = true;
|
||||
if (!res.conversation.running) {
|
||||
setMessages(res.messages);
|
||||
setBusy(false);
|
||||
return;
|
||||
}
|
||||
// Still answering: show what is saved up to the question, then replay the live turn.
|
||||
const lastUser = res.messages.map((m) => m.role).lastIndexOf('user');
|
||||
const pendingId = `p${Date.now()}`;
|
||||
setMessages([...res.messages.slice(0, lastUser + 1), { id: pendingId, role: 'assistant', text: '', tools: [], ui: [], createdAt: Date.now(), pending: true }]);
|
||||
setLoadingHistory(false);
|
||||
void follow(pendingId, (signal, onEvent) => streamEvents<AssistantEvent>(`/api/ai/chat/${id}/stream`, undefined, onEvent, signal));
|
||||
} catch {
|
||||
setConversation(null);
|
||||
setMessages([]);
|
||||
} finally {
|
||||
setLoadingHistory(false);
|
||||
}
|
||||
},
|
||||
[follow, setConversation],
|
||||
);
|
||||
|
||||
// Open the remembered or routed conversation on mount.
|
||||
useEffect(() => {
|
||||
if (initialConversation) void load(initialConversation);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (routeConversationId && routeConversationId !== conversationId) void load(routeConversationId);
|
||||
if (!routeConversationId && variant === 'page' && conversationId && !busy) {
|
||||
setConversationId(null);
|
||||
if (variant !== 'page') return;
|
||||
if (routeConversationId && routeConversationId !== conversationRef.current) void load(routeConversationId);
|
||||
if (!routeConversationId && conversationRef.current && !busy) {
|
||||
setConversation(null);
|
||||
setMessages([]);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [routeConversationId]);
|
||||
|
||||
const newChat = useCallback(() => {
|
||||
abort.current?.abort();
|
||||
setConversationId(null);
|
||||
// Detach only: an answer still being written keeps going and is saved in its conversation.
|
||||
stream.current?.abort();
|
||||
setBusy(false);
|
||||
setConversation(null);
|
||||
setMessages([]);
|
||||
setFocusDocs([]);
|
||||
setTags([]);
|
||||
onConversationChange?.(null);
|
||||
setTimeout(() => inputRef.current?.focus(), 30);
|
||||
}, [onConversationChange]);
|
||||
}, [onConversationChange, setConversation]);
|
||||
|
||||
const stop = useCallback(() => {
|
||||
stopRequested.current = true;
|
||||
const id = conversationRef.current;
|
||||
if (id) void api.post(`/api/ai/chat/${id}/stop`).catch(() => undefined);
|
||||
}, []);
|
||||
|
||||
const activeDocs = focusDocs.length > 0 ? focusDocs : context.documentIds;
|
||||
const className = classes.data?.find((c) => c.id === context.classId)?.name;
|
||||
|
|
@ -244,47 +431,37 @@ export default function AssistantPanel({
|
|||
async (text: string, opts: { conversationId?: string | null; documentIds?: string[]; classId?: string | null } = {}) => {
|
||||
const message = text.trim();
|
||||
if (!message || busy) return;
|
||||
const convo = opts.conversationId !== undefined ? opts.conversationId : conversationId;
|
||||
setBusy(true);
|
||||
const convo = opts.conversationId !== undefined ? opts.conversationId : conversationRef.current;
|
||||
const sentTags = tags;
|
||||
setInput('');
|
||||
setTags([]);
|
||||
setMention(null);
|
||||
stick.current = true;
|
||||
const pendingId = `p${Date.now()}`;
|
||||
setMessages((m) => [...m, { id: `u${Date.now()}`, role: 'user', text: message, tools: [], ui: [], createdAt: Date.now() }, { id: pendingId, role: 'assistant', text: '', tools: [], ui: [], createdAt: Date.now(), pending: true }]);
|
||||
const patch = (fn: (m: ChatMessage) => ChatMessage) => setMessages((list) => list.map((m) => (m.id === pendingId ? fn(m) : m)));
|
||||
const controller = new AbortController();
|
||||
abort.current = controller;
|
||||
let newId: string | null = null;
|
||||
try {
|
||||
await streamEvents<AssistantEvent>(
|
||||
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 },
|
||||
]);
|
||||
await follow(pendingId, (signal, onEvent) =>
|
||||
streamEvents<AssistantEvent>(
|
||||
'/api/ai/chat',
|
||||
{ conversationId: convo, message, context: { classId: opts.classId !== undefined ? opts.classId : context.classId, documentIds: opts.documentIds ?? activeDocs } },
|
||||
(e) => {
|
||||
if (e.type === 'start') {
|
||||
newId = e.conversationId;
|
||||
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 }));
|
||||
{
|
||||
conversationId: convo,
|
||||
message,
|
||||
modelId: effectiveModelId || undefined,
|
||||
context: {
|
||||
classId: opts.classId !== undefined ? opts.classId : context.classId,
|
||||
documentIds: opts.documentIds ?? activeDocs,
|
||||
items: sentTags.map((t) => ({ kind: t.kind, id: t.id })),
|
||||
},
|
||||
},
|
||||
controller.signal,
|
||||
);
|
||||
} catch (e) {
|
||||
if ((e as Error)?.name !== 'AbortError') patch((m) => ({ ...m, error: errorMessage(e) }));
|
||||
} finally {
|
||||
patch((m) => ({ ...m, pending: false, tools: m.tools.map((t) => (t.status === 'running' ? { ...t, status: 'error', summary: 'Stopped' } : t)), text: m.text || (m.error || m.ui.length || m.tools.length ? m.text : controller.signal.aborted ? '*(Stopped.)*' : m.text) }));
|
||||
setBusy(false);
|
||||
if (newId && newId !== convo) {
|
||||
setConversationId(newId);
|
||||
onConversationChange?.(newId);
|
||||
}
|
||||
void qc.invalidateQueries({ queryKey: ['ai', 'conversations'] });
|
||||
// Tools may have created drafts, classes or sessions.
|
||||
void refresh();
|
||||
}
|
||||
onEvent,
|
||||
signal,
|
||||
),
|
||||
);
|
||||
},
|
||||
[busy, conversationId, context.classId, activeDocs, onConversationChange, qc, refresh],
|
||||
[busy, tags, follow, effectiveModelId, context.classId, activeDocs],
|
||||
);
|
||||
|
||||
// Requests from elsewhere in the app ("Ask about this document", "New questions on these topics").
|
||||
|
|
@ -293,8 +470,9 @@ export default function AssistantPanel({
|
|||
handledSeed.current = seed.id;
|
||||
assistant.consumeSeed();
|
||||
if (seed.newChat) {
|
||||
abort.current?.abort();
|
||||
setConversationId(null);
|
||||
stream.current?.abort();
|
||||
setBusy(false);
|
||||
setConversation(null);
|
||||
setMessages([]);
|
||||
onConversationChange?.(null);
|
||||
}
|
||||
|
|
@ -304,14 +482,15 @@ export default function AssistantPanel({
|
|||
if (seed.prompt) setInput(seed.prompt);
|
||||
setTimeout(() => inputRef.current?.focus(), 60);
|
||||
}
|
||||
}, [seed, ai.data, send, onConversationChange]);
|
||||
}, [seed, ai.data, send, onConversationChange, setConversation]);
|
||||
|
||||
// Keep the newest content in view unless the user has scrolled up to read.
|
||||
useEffect(() => {
|
||||
const el = scroller.current;
|
||||
if (el && stick.current) el.scrollTop = el.scrollHeight;
|
||||
}, [messages]);
|
||||
useEffect(() => () => abort.current?.abort(), []);
|
||||
// Leaving only disconnects; the server finishes the answer and saves it.
|
||||
useEffect(() => () => stream.current?.abort(), []);
|
||||
|
||||
const updateAction = (actionId: string, status: string, result: string) => {
|
||||
setMessages((list) => list.map((m) => ({ ...m, ui: m.ui.map((u) => (u.type === 'action' && u.actionId === actionId ? { ...u, status: status as typeof u.status, result } : u)) })));
|
||||
|
|
@ -329,16 +508,54 @@ export default function AssistantPanel({
|
|||
}, [activeDocs.length, className]);
|
||||
|
||||
const contextLabel = activeDocs.length > 0 ? (context.documentIds.length && context.label ? context.label : plural(activeDocs.length, 'document')) : className;
|
||||
const options = useMentionables(context.classId, mention?.query ?? '', mention !== null);
|
||||
const pickable = options.filter((o) => !tags.some((t) => t.kind === o.kind && t.id === o.id));
|
||||
|
||||
const updateMention = (text: string, caret: number) => {
|
||||
const next = mentionAt(text, caret);
|
||||
setMention(next);
|
||||
if (!next || next.query !== mention?.query) setMentionIndex(0);
|
||||
};
|
||||
const choose = (item: Mentionable) => {
|
||||
setTags((t) => (t.some((x) => x.kind === item.kind && x.id === item.id) ? t : [...t, { kind: item.kind, id: item.id, title: item.title }]));
|
||||
if (mention) {
|
||||
const caret = inputRef.current?.selectionStart ?? input.length;
|
||||
const next = `${input.slice(0, mention.start)}${input.slice(caret)}`.replace(/\s{2,}/g, ' ');
|
||||
setInput(next);
|
||||
setTimeout(() => {
|
||||
const el = inputRef.current;
|
||||
if (el) {
|
||||
el.focus();
|
||||
el.setSelectionRange(mention.start, mention.start);
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
setMention(null);
|
||||
};
|
||||
const openPicker = () => {
|
||||
const el = inputRef.current;
|
||||
const caret = el?.selectionStart ?? input.length;
|
||||
const needsSpace = caret > 0 && !/\s/.test(input[caret - 1] ?? '');
|
||||
const next = `${input.slice(0, caret)}${needsSpace ? ' ' : ''}@${input.slice(caret)}`;
|
||||
setInput(next);
|
||||
const at = caret + (needsSpace ? 1 : 0) + 1;
|
||||
setMention({ start: at - 1, query: '' });
|
||||
setMentionIndex(0);
|
||||
setTimeout(() => {
|
||||
el?.focus();
|
||||
el?.setSelectionRange(at, at);
|
||||
}, 0);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col">
|
||||
<header className={cx('flex h-14 shrink-0 items-center gap-2 border-b border-line px-3', variant === 'page' && 'lg:px-0')}>
|
||||
<span className="grid size-8 place-items-center rounded-[10px] bg-ink text-marker">
|
||||
<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" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-sm font-semibold">Assistant</div>
|
||||
<div className="truncate text-xs text-ink-3">{ai.data?.resolved.chat ? ai.data.resolved.chat.label : ai.data && !ai.data.ready ? 'Not set up' : ''}</div>
|
||||
{ai.data?.ready ? <ModelPicker value={effectiveModelId} onChange={setModelId} defaultLabel={ai.data.resolved.chat?.label} /> : <div className="truncate text-xs text-ink-3">{ai.data ? 'Not set up' : ''}</div>}
|
||||
</div>
|
||||
<IconButton label="New chat" size="sm" onClick={newChat}>
|
||||
<Plus />
|
||||
|
|
@ -354,7 +571,7 @@ export default function AssistantPanel({
|
|||
<MenuLabel>Recent conversations</MenuLabel>
|
||||
{(history.data ?? []).length === 0 && <div className="px-2.5 py-2 text-[13px] text-ink-3">Nothing yet</div>}
|
||||
{(history.data ?? []).slice(0, 12).map((c) => (
|
||||
<MenuItem key={c.id} onSelect={() => load(c.id)} hint={timeAgo(c.updatedAt)}>
|
||||
<MenuItem key={c.id} onSelect={() => load(c.id)} hint={c.running ? 'working…' : timeAgo(c.updatedAt)}>
|
||||
{c.title}
|
||||
</MenuItem>
|
||||
))}
|
||||
|
|
@ -365,7 +582,9 @@ export default function AssistantPanel({
|
|||
icon={<Trash2 />}
|
||||
danger
|
||||
onSelect={async () => {
|
||||
await api.del(`/api/ai/conversations/${conversationId}`).catch(() => undefined);
|
||||
const id = conversationId;
|
||||
stop();
|
||||
await api.del(`/api/ai/conversations/${id}`).catch(() => undefined);
|
||||
void qc.invalidateQueries({ queryKey: ['ai', 'conversations'] });
|
||||
newChat();
|
||||
}}
|
||||
|
|
@ -385,7 +604,7 @@ export default function AssistantPanel({
|
|||
const el = e.currentTarget;
|
||||
stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80;
|
||||
}}
|
||||
className={cx('min-h-0 flex-1 overflow-y-auto px-4 py-5', variant === 'page' && 'lg:px-1')}
|
||||
className={cx('min-h-0 flex-1 overflow-y-auto px-4 py-5', variant === 'page' && 'lg:px-6')}
|
||||
aria-live="polite"
|
||||
>
|
||||
{ai.isLoading || loadingHistory ? (
|
||||
|
|
@ -395,18 +614,18 @@ export default function AssistantPanel({
|
|||
) : !ai.data?.ready ? (
|
||||
<div className="mx-auto max-w-sm pt-8">
|
||||
<Callout tone="accent" icon={<Sparkles />} title="Connect an AI model to use the assistant">
|
||||
Add a provider such as OpenAI, Anthropic, Google Gemini or a local model, then switch on a model.
|
||||
Add a provider such as OpenAI, Anthropic, Google Gemini, DeepSeek or a local model, then switch on a model.
|
||||
<div className="mt-3">
|
||||
<Button to="/settings/ai" onClick={() => variant === 'drawer' && assistant.close()} size="sm" variant="primary">
|
||||
Open AI settings
|
||||
</Button>
|
||||
Open AI settings
|
||||
</Button>
|
||||
</div>
|
||||
</Callout>
|
||||
</div>
|
||||
) : 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.</p>
|
||||
<p className="mt-1.5 text-sm text-ink-2">I can read your documents, look at your results, and prepare quizzes, flashcards and study guides for you to review. Type @ to point me at a specific quiz, deck, note or document.</p>
|
||||
<div className="mt-5 space-y-2">
|
||||
{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">
|
||||
|
|
@ -421,7 +640,16 @@ export default function AssistantPanel({
|
|||
{messages.map((m) =>
|
||||
m.role === 'user' ? (
|
||||
<div key={m.id} className="flex justify-end">
|
||||
<div className="max-w-[88%] rounded-[16px] rounded-br-md bg-ink px-3.5 py-2.5 text-[15px] whitespace-pre-wrap text-paper">{m.text}</div>
|
||||
<div className="max-w-[88%] rounded-[16px] rounded-br-md bg-ink px-3.5 py-2.5 text-[15px] whitespace-pre-wrap text-paper">
|
||||
{m.tags?.length ? (
|
||||
<div className="mb-1.5 flex flex-wrap gap-1">
|
||||
{m.tags.map((t) => (
|
||||
<TagChip key={`${t.kind}:${t.id}`} item={t} inverted />
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
{m.text}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<AssistantMessage key={m.id} message={m} onNavigate={() => variant === 'drawer' && window.innerWidth < 1360 && assistant.close()} onAction={updateAction} />
|
||||
|
|
@ -432,8 +660,8 @@ export default function AssistantPanel({
|
|||
</div>
|
||||
|
||||
{ai.data?.ready && (
|
||||
<div className={cx('safe-bottom shrink-0 border-t border-line px-3 pt-2.5 pb-3', variant === 'page' && 'lg:px-0')}>
|
||||
<div className="mx-auto max-w-2xl">
|
||||
<div className={cx('safe-pb-3 shrink-0 border-t border-line px-3 pt-2.5', variant === 'page' && 'lg:px-6')}>
|
||||
<div className="relative mx-auto max-w-2xl">
|
||||
{contextLabel && (
|
||||
<div className="mb-2 flex items-center gap-1.5">
|
||||
<Badge tone="accent" className="max-w-full">
|
||||
|
|
@ -447,41 +675,104 @@ export default function AssistantPanel({
|
|||
)}
|
||||
</div>
|
||||
)}
|
||||
{mention && (
|
||||
<div role="listbox" aria-label="Tag a material" className="absolute inset-x-0 bottom-full z-30 mb-2 max-h-72 overflow-y-auto rounded-xl border border-line bg-surface p-1.5 shadow-2">
|
||||
<div className="eyebrow px-2 pt-1 pb-1.5">{context.classId ? `Materials in ${className ?? 'this class'}` : 'Your library'}</div>
|
||||
{pickable.length === 0 ? (
|
||||
<div className="px-2.5 py-2 text-[13px] text-ink-3">{context.classId || mention.query ? 'Nothing matches.' : 'Type to search your quizzes, decks, notes and documents.'}</div>
|
||||
) : (
|
||||
pickable.map((o, i) => (
|
||||
<button
|
||||
key={`${o.kind}:${o.id}`}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={i === mentionIndex}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onMouseMove={() => setMentionIndex(i)}
|
||||
onClick={() => choose(o)}
|
||||
className={cx('flex w-full items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left', i === mentionIndex && 'bg-ink/7')}
|
||||
>
|
||||
<span className="grid size-7 shrink-0 place-items-center rounded-md bg-sunken text-ink-2 [&>svg]:size-3.5">{TAG_ICON[o.kind]}</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-sm">{o.title}</span>
|
||||
<span className="block truncate text-[11px] text-ink-3">
|
||||
{TAG_NOUN[o.kind]}
|
||||
{o.folderName ? ` · ${o.folderName}` : ''}
|
||||
{!context.classId ? ` · ${o.className}` : ''}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<form
|
||||
className="flex items-end gap-2 rounded-[16px] border border-line-strong bg-surface p-1.5 shadow-1 focus-within:border-accent focus-within:ring-2 focus-within:ring-accent/20"
|
||||
className="rounded-[16px] border border-line-strong bg-surface p-1.5 shadow-1 focus-within:border-accent focus-within:ring-2 focus-within:ring-accent/20"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (busy) abort.current?.abort();
|
||||
if (busy) stop();
|
||||
else void send(input);
|
||||
}}
|
||||
>
|
||||
<textarea
|
||||
ref={inputRef}
|
||||
value={input}
|
||||
rows={1}
|
||||
onChange={(e) => {
|
||||
setInput(e.target.value);
|
||||
e.target.style.height = 'auto';
|
||||
e.target.style.height = `${Math.min(e.target.scrollHeight, 180)}px`;
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
|
||||
e.preventDefault();
|
||||
if (!busy) void send(input);
|
||||
}
|
||||
}}
|
||||
placeholder="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"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!busy && !input.trim()}
|
||||
aria-label={busy ? 'Stop' : 'Send'}
|
||||
className={cx('grid size-9 shrink-0 place-items-center rounded-[11px] transition-colors disabled:opacity-35', busy ? 'bg-sunken text-ink' : 'bg-ink text-paper hover:bg-ink/85')}
|
||||
>
|
||||
{busy ? <Square className="size-3.5 fill-current" /> : <ArrowUp className="size-[18px]" />}
|
||||
</button>
|
||||
{tags.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1 px-1.5 pt-1 pb-1.5">
|
||||
{tags.map((t) => (
|
||||
<TagChip key={`${t.kind}:${t.id}`} item={t} onRemove={() => setTags((list) => list.filter((x) => !(x.kind === t.kind && x.id === t.id)))} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-end gap-1.5">
|
||||
<textarea
|
||||
ref={inputRef}
|
||||
value={input}
|
||||
rows={1}
|
||||
onChange={(e) => {
|
||||
setInput(e.target.value);
|
||||
updateMention(e.target.value, e.target.selectionStart ?? e.target.value.length);
|
||||
e.target.style.height = 'auto';
|
||||
e.target.style.height = `${Math.min(e.target.scrollHeight, 180)}px`;
|
||||
}}
|
||||
onSelect={(e) => mention && updateMention(e.currentTarget.value, e.currentTarget.selectionStart ?? 0)}
|
||||
onBlur={() => setTimeout(() => setMention(null), 120)}
|
||||
onKeyDown={(e) => {
|
||||
if (mention && pickable.length > 0) {
|
||||
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
setMentionIndex((i) => (i + (e.key === 'ArrowDown' ? 1 : -1) + pickable.length) % pickable.length);
|
||||
return;
|
||||
}
|
||||
if (e.key === 'Enter' || e.key === 'Tab') {
|
||||
e.preventDefault();
|
||||
choose(pickable[Math.min(mentionIndex, pickable.length - 1)]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (mention && e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
setMention(null);
|
||||
return;
|
||||
}
|
||||
if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
|
||||
e.preventDefault();
|
||||
if (!busy) void send(input);
|
||||
}
|
||||
}}
|
||||
placeholder={context.classId ? 'Ask anything. Type @ to tag a quiz, deck, note or document…' : 'Ask anything, or describe what to create…'}
|
||||
aria-label="Message the assistant"
|
||||
className="max-h-44 min-h-9 flex-1 resize-none bg-transparent px-2.5 py-1.5 text-[15px] outline-none placeholder:text-ink-3"
|
||||
/>
|
||||
<IconButton label="Tag a material" size="sm" className="mb-0.5" onClick={openPicker}>
|
||||
<AtSign />
|
||||
</IconButton>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!busy && !input.trim()}
|
||||
aria-label={busy ? 'Stop' : 'Send'}
|
||||
className={cx('grid size-9 shrink-0 place-items-center rounded-[11px] transition-colors disabled:opacity-35', busy ? 'bg-sunken text-ink' : 'bg-ink text-paper hover:bg-ink/85')}
|
||||
>
|
||||
{busy ? <Square className="size-3.5 fill-current" /> : <ArrowUp className="size-[18px]" />}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
<p className="mt-1.5 px-1 text-[11px] text-ink-3">Drafts and changes always wait for your approval. AI can make mistakes: verify clinical facts.</p>
|
||||
</div>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue