diff --git a/src/api/chatbot/types.ts b/src/api/chatbot/types.ts index fc8b59e..18898d1 100644 --- a/src/api/chatbot/types.ts +++ b/src/api/chatbot/types.ts @@ -9,6 +9,9 @@ export type ChatbotThread = { export type ChatbotThreadBody = { title?: string | null }; +/** Where an answer offers to take the user, rendered as a button under it. */ +export type ChatbotNavigation = { route: string; label: string }; + export type ChatbotMessage = { id: string; thread_id: string; @@ -19,6 +22,14 @@ export type ChatbotMessage = { error_code: string | null; created_at: number; completed_at: number | null; + /** + * Optional halves of `chat.reply`: a place the answer can take the user, and + * the follow-up questions it offers when it is not sure what was meant. Both + * are absent until the backend sends them, and the panel renders nothing for + * an answer that carries neither. + */ + navigation?: ChatbotNavigation | null; + suggestions?: string[] | null; }; export type AcceptedChatbotMessage = { diff --git a/src/components/layout/celebi-panel.tsx b/src/components/layout/celebi-panel.tsx index 3ce3269..73313b8 100644 --- a/src/components/layout/celebi-panel.tsx +++ b/src/components/layout/celebi-panel.tsx @@ -1,8 +1,10 @@ -import { For, Show, createEffect, createSignal, onCleanup } from "solid-js"; +import { For, Match, Show, Switch, createEffect, createSignal, onCleanup } from "solid-js"; +import { useNavigate } from "@tanstack/solid-router"; import { deleteChatbotThreadById, getChatbotMessageById, getChatbotThreadMessages, getChatbotThreads, patchChatbotThreadById, postChatbotMessage, postChatbotThread, type ChatbotMessage, type ChatbotThread } from "@/api/chatbot"; import { formatApiError } from "@/api/client"; import { CelebiComposer } from "@/components/layout/celebi-composer"; import { CelebiMarkdown } from "@/components/layout/celebi-markdown"; +import { CelebiReplyActions } from "@/components/layout/celebi-reply-actions"; import { CelebiSuggestions } from "@/components/layout/celebi-suggestions"; import { CelebiThinkingLabel } from "@/components/layout/celebi-thinking-label"; import { IconAlert, IconBotSquare, IconCopy, IconEdit, IconPlus, IconSparkles, IconTrash } from "@/components/ui/icons"; @@ -10,12 +12,20 @@ import { SidePanel } from "@/components/ui/side-panel"; import { cn } from "@/lib/cn"; import { usePreferences, useT } from "@/stores/preferences-context"; -type PanelMessage = Pick; +type PanelMessage = Pick; const POLL_INTERVAL_MS = 1_000; +// A comfortable reading pace for the reveal, and the backlog past which it +// stops pacing and catches up: a rule-based answer often lands whole in the +// `done` event, and nobody should wait out an animation to read it. +const REVEAL_CHARS_PER_SECOND = 90; +const REVEAL_CATCH_UP_CHARS = 320; +const REVEAL_CATCH_UP_FACTOR = 5; + export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean) => void }) { const t = useT(); + const navigate = useNavigate(); const { locale } = usePreferences(); const [draft, setDraft] = createSignal(""); const [messages, setMessages] = createSignal([]); @@ -30,6 +40,52 @@ export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean window.setTimeout(() => setCopiedId((current) => (current === message.id ? undefined : current)), 1_500); }; + // Answers arrive either as stream deltas or whole in the `done` event, and + // both used to appear in one jump. The reveal walks a character count over + // whatever content the answer has so far, so a streamed answer types itself + // and a whole one is still read at a human pace. Reduced motion skips it. + const [typingId, setTypingId] = createSignal(); + const [typedCount, setTypedCount] = createSignal(0); + let revealFrame: number | undefined; + + const prefersReducedMotion = () => + typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches; + + const stopReveal = () => { + if (revealFrame !== undefined) cancelAnimationFrame(revealFrame); + revealFrame = undefined; + setTypingId(undefined); + }; + + const startReveal = (messageId: string) => { + stopReveal(); + if (prefersReducedMotion()) return; + setTypingId(messageId); + setTypedCount(0); + let previous = performance.now(); + const step = (now: number) => { + const target = messages().find((item) => item.id === messageId); + if (!target || typingId() !== messageId) return stopReveal(); + const full = target.content.length; + const behind = full - typedCount(); + const speed = REVEAL_CHARS_PER_SECOND * (behind > REVEAL_CATCH_UP_CHARS ? REVEAL_CATCH_UP_FACTOR : 1); + setTypedCount((count) => Math.min(full, count + ((now - previous) / 1_000) * speed)); + previous = now; + // Keep the frame running while the answer is still being written, even + // once the text in hand is exhausted: the next delta extends it. + if (typedCount() >= full && target.status !== "pending") return stopReveal(); + revealFrame = requestAnimationFrame(step); + }; + revealFrame = requestAnimationFrame(step); + }; + + /** How much of a message is on screen — the whole of it unless it is the one revealing. */ + const visibleContent = (message: PanelMessage) => + message.id === typingId() ? message.content.slice(0, Math.floor(typedCount())) : message.content; + + const isRevealing = (message: PanelMessage) => + message.id === typingId() && (message.status === "pending" || Math.floor(typedCount()) < message.content.length); + // The transcript follows the newest message, but only while the reader is // already at the bottom: scrolling up to re-read an earlier answer must not // be yanked back down by the next streamed chunk. @@ -41,6 +97,7 @@ export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean }; createEffect(() => { const items = messages(); + typedCount(); if (!transcript || items.length === 0) return; const distance = transcript.scrollHeight - transcript.scrollTop - transcript.clientHeight; const atBottom = distance <= NEAR_BOTTOM_PX; @@ -58,8 +115,8 @@ export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean }; const stopStream = () => { stream?.close(); stream = undefined; }; const loadThreads = async () => { try { setThreads((await getChatbotThreads({ limit: 100 })).items); } catch { /* history is non-blocking */ } }; - const openThread = async (id: string) => { stopPolling(); stopStream(); setThreadId(id); setMessages((await getChatbotThreadMessages(id, { limit: 500 })).items); }; - const createThread = () => { stopPolling(); stopStream(); setThreadId(undefined); setMessages([]); }; + const openThread = async (id: string) => { stopPolling(); stopStream(); stopReveal(); setThreadId(id); setMessages((await getChatbotThreadMessages(id, { limit: 500 })).items); }; + const createThread = () => { stopPolling(); stopStream(); stopReveal(); setThreadId(undefined); setMessages([]); }; const renameThread = async (thread: ChatbotThread) => { const title = window.prompt(locale() === "tr" ? "Sohbet başlığı" : "Conversation title", thread.title ?? ""); if (title !== null) { await patchChatbotThreadById(thread.id, { title: title.trim() || null }); await loadThreads(); } }; const removeThread = async (thread: ChatbotThread) => { if (!window.confirm(locale() === "tr" ? "Bu sohbet silinsin mi?" : "Delete this conversation?")) return; await deleteChatbotThreadById(thread.id); if (threadId() === thread.id) createThread(); await loadThreads(); }; createEffect(() => { if (props.open) void loadThreads(); }); @@ -97,7 +154,7 @@ export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean source.onerror = () => { stopStream(); poll(activeThreadId, messageId); }; }; - onCleanup(() => { stopPolling(); stopStream(); }); + onCleanup(() => { stopPolling(); stopStream(); stopReveal(); }); const send = async (override?: string) => { // A suggestion chip sends its own text without ever touching the draft. @@ -127,6 +184,7 @@ export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean completed_at: null, }, ]); + startReveal(accepted.message_id); streamAnswer(activeThreadId, accepted.message_id); void loadThreads(); } catch (error) { @@ -190,23 +248,52 @@ export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean {(message) => (
- {message.content}

}> - -
- }> + + +

{message.content}

+
+

{failureMessage(message.error_code)}

- - }> - - +
+ {/* The label stands in only until the first characters land; + an answer that is still being written keeps typing. */} + + + + + + + + +
{failureMessage(message.error_code)}

{locale() === "tr" ? "Yanıt uzunluk sınırında kısaltıldı." : "Response was shortened at the configured limit."}

+ + { + props.onOpenChange(false); + // The route is checked in celebi-route.ts, but it is a + // runtime string either way — the router's typed table + // cannot describe it. + void navigate({ to: route as never }); + }} + onPick={(text) => void send(text)} + /> + + )} + + + 0}> +
+

+ + {t("ai.didYouMean")} +

+
+ + {(text) => ( + + )} + +
+
+
+
+ + ); +} diff --git a/src/i18n/messages.ts b/src/i18n/messages.ts index d5dbe1b..f2aaa9d 100644 --- a/src/i18n/messages.ts +++ b/src/i18n/messages.ts @@ -28,6 +28,9 @@ export type MessageKey = | "ai.suggestParent2" | "ai.suggestParent3" | "ai.suggestParent4" + | "ai.goTo" + | "ai.didYouMean" + | "ai.skipTyping" | "nav.today" | "nav.classes" | "nav.classGroups" @@ -1557,6 +1560,9 @@ const en: Dict = { "ai.suggestParent2": "Which exams does my child have soon?", "ai.suggestParent3": "How is my child's attendance this term?", "ai.suggestParent4": "What is on this week's meal menu?", + "ai.goTo": "Go to the page", + "ai.didYouMean": "Did you mean one of these?", + "ai.skipTyping": "Show the whole answer", "nav.today": "Today", "nav.classes": "Education", "nav.classGroups": "Classes", @@ -3097,6 +3103,9 @@ const tr: Dict = { "ai.suggestParent2": "Çocuğumun yaklaşan sınavları neler?", "ai.suggestParent3": "Çocuğumun bu dönem devamsızlığı nasıl?", "ai.suggestParent4": "Bu haftanın yemek menüsünde ne var?", + "ai.goTo": "Sayfaya git", + "ai.didYouMean": "Bunu mu demek istedin?", + "ai.skipTyping": "Cevabın tamamını göster", "nav.today": "Bugün", "nav.classes": "Eğitim", "nav.classGroups": "Şubeler", diff --git a/src/lib/celebi-route.test.ts b/src/lib/celebi-route.test.ts new file mode 100644 index 0000000..b1c2b79 --- /dev/null +++ b/src/lib/celebi-route.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from "vitest"; +import { safeCelebiRoute } from "./celebi-route"; + +describe("safeCelebiRoute", () => { + it("keeps an in-app path, trimmed", () => { + expect(safeCelebiRoute("/exams")).toBe("/exams"); + expect(safeCelebiRoute(" /management/classes/abc ")).toBe("/management/classes/abc"); + expect(safeCelebiRoute("/calendar?view=week")).toBe("/calendar?view=week"); + }); + + it("rejects anything that could leave the app", () => { + expect(safeCelebiRoute("//evil.example/phish")).toBeNull(); + expect(safeCelebiRoute("/\\evil.example")).toBeNull(); + expect(safeCelebiRoute("https://evil.example")).toBeNull(); + expect(safeCelebiRoute("javascript:alert(1)")).toBeNull(); + expect(safeCelebiRoute("exams")).toBeNull(); + }); + + it("rejects a path that is not one", () => { + expect(safeCelebiRoute("/exams and more")).toBeNull(); + expect(safeCelebiRoute("/exams\nHost: evil")).toBeNull(); + expect(safeCelebiRoute("")).toBeNull(); + expect(safeCelebiRoute(null)).toBeNull(); + expect(safeCelebiRoute(undefined)).toBeNull(); + }); +}); diff --git a/src/lib/celebi-route.ts b/src/lib/celebi-route.ts new file mode 100644 index 0000000..2858a1e --- /dev/null +++ b/src/lib/celebi-route.ts @@ -0,0 +1,16 @@ +/** + * An answer may offer to take the user somewhere. The route arrives from the + * backend, so it is treated as data: only an in-app absolute path is accepted, + * which keeps `//evil.example` (protocol-relative), `javascript:` and every + * other off-site target from ever reaching the router. + */ +export function safeCelebiRoute(route: string | null | undefined): string | null { + if (typeof route !== "string") return null; + const trimmed = route.trim(); + if (!trimmed.startsWith("/")) return null; + if (trimmed.startsWith("//") || trimmed.startsWith("/\\")) return null; + // Printable ASCII without spaces: a route is a path, and anything else in it + // (control characters, line breaks) means it is not one. + if (!/^[\x21-\x7e]+$/.test(trimmed)) return null; + return trimmed; +} diff --git a/vitest.config.ts b/vitest.config.ts index b55f6e4..da877df 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -26,7 +26,11 @@ export default defineConfig({ }, }, { - plugins: [solid()], + // `hot: false`: the plugin otherwise injects solid-refresh's virtual + // module, and vitest hands node the unresolvable `file:///@solid-refresh` + // specifier — every *.test.tsx file failed to load on that alone. There + // is no HMR in a test run for it to serve. + plugins: [solid({ hot: false })], // "development"/"browser" so solid-js resolves to its client build once — // a dual-loaded solid-js gives components a different reactive graph. resolve: { alias, conditions: ["development", "browser"] },