💬 Çelebi types its answer, follows it, and offers where to go next
Browse files at this commit6f3078573a64b2b5818644dc685be8a97d201e13Parent: 4d56b03- feat
- 💬 Çelebi types its answer, follows it, and offers where to go next
8 changed files +285 -16
- src/api/chatbot/types.ts +11 -0
- src/components/layout/celebi-panel.tsx +102 -15
- src/components/layout/celebi-reply-actions.test.tsx +50 -0
- src/components/layout/celebi-reply-actions.tsx +66 -0
- src/i18n/messages.ts +9 -0
- src/lib/celebi-route.test.ts +26 -0
- src/lib/celebi-route.ts +16 -0
- vitest.config.ts +5 -1
src/api/chatbot/types.tsmodified+11 -0
| @@ -9,6 +9,9 @@ export type ChatbotThread = { | |||
| 9 | 9 | ||
| 10 | export type ChatbotThreadBody = { title?: string | null }; | 10 | export type ChatbotThreadBody = { title?: string | null }; |
| 11 | 11 | ||
| 12 | +/** Where an answer offers to take the user, rendered as a button under it. */ | ||
| 13 | +export type ChatbotNavigation = { route: string; label: string }; | ||
| 14 | + | ||
| 12 | export type ChatbotMessage = { | 15 | export type ChatbotMessage = { |
| 13 | id: string; | 16 | id: string; |
| 14 | thread_id: string; | 17 | thread_id: string; |
| @@ -19,6 +22,14 @@ export type ChatbotMessage = { | |||
| 19 | error_code: string | null; | 22 | error_code: string | null; |
| 20 | created_at: number; | 23 | created_at: number; |
| 21 | completed_at: number | null; | 24 | completed_at: number | null; |
| 25 | + /** | ||
| 26 | + * Optional halves of `chat.reply`: a place the answer can take the user, and | ||
| 27 | + * the follow-up questions it offers when it is not sure what was meant. Both | ||
| 28 | + * are absent until the backend sends them, and the panel renders nothing for | ||
| 29 | + * an answer that carries neither. | ||
| 30 | + */ | ||
| 31 | + navigation?: ChatbotNavigation | null; | ||
| 32 | + suggestions?: string[] | null; | ||
| 22 | }; | 33 | }; |
| 23 | 34 | ||
| 24 | export type AcceptedChatbotMessage = { | 35 | export type AcceptedChatbotMessage = { |
src/components/layout/celebi-panel.tsxmodified+102 -15
| @@ -1,8 +1,10 @@ | |||
| 1 | -import { For, Show, createEffect, createSignal, onCleanup } from "solid-js"; | 1 | +import { For, Match, Show, Switch, createEffect, createSignal, onCleanup } from "solid-js"; |
| 2 | +import { useNavigate } from "@tanstack/solid-router"; | ||
| 2 | import { deleteChatbotThreadById, getChatbotMessageById, getChatbotThreadMessages, getChatbotThreads, patchChatbotThreadById, postChatbotMessage, postChatbotThread, type ChatbotMessage, type ChatbotThread } from "@/api/chatbot"; | 3 | import { deleteChatbotThreadById, getChatbotMessageById, getChatbotThreadMessages, getChatbotThreads, patchChatbotThreadById, postChatbotMessage, postChatbotThread, type ChatbotMessage, type ChatbotThread } from "@/api/chatbot"; |
| 3 | import { formatApiError } from "@/api/client"; | 4 | import { formatApiError } from "@/api/client"; |
| 4 | import { CelebiComposer } from "@/components/layout/celebi-composer"; | 5 | import { CelebiComposer } from "@/components/layout/celebi-composer"; |
| 5 | import { CelebiMarkdown } from "@/components/layout/celebi-markdown"; | 6 | import { CelebiMarkdown } from "@/components/layout/celebi-markdown"; |
| 7 | +import { CelebiReplyActions } from "@/components/layout/celebi-reply-actions"; | ||
| 6 | import { CelebiSuggestions } from "@/components/layout/celebi-suggestions"; | 8 | import { CelebiSuggestions } from "@/components/layout/celebi-suggestions"; |
| 7 | import { CelebiThinkingLabel } from "@/components/layout/celebi-thinking-label"; | 9 | import { CelebiThinkingLabel } from "@/components/layout/celebi-thinking-label"; |
| 8 | import { IconAlert, IconBotSquare, IconCopy, IconEdit, IconPlus, IconSparkles, IconTrash } from "@/components/ui/icons"; | 10 | import { IconAlert, IconBotSquare, IconCopy, IconEdit, IconPlus, IconSparkles, IconTrash } from "@/components/ui/icons"; |
| @@ -10,12 +12,20 @@ import { SidePanel } from "@/components/ui/side-panel"; | |||
| 10 | import { cn } from "@/lib/cn"; | 12 | import { cn } from "@/lib/cn"; |
| 11 | import { usePreferences, useT } from "@/stores/preferences-context"; | 13 | import { usePreferences, useT } from "@/stores/preferences-context"; |
| 12 | 14 | ||
| 13 | -type PanelMessage = Pick<ChatbotMessage, "id" | "role" | "status" | "content" | "truncated" | "error_code">; | 15 | +type PanelMessage = Pick<ChatbotMessage, "id" | "role" | "status" | "content" | "truncated" | "error_code" | "navigation" | "suggestions">; |
| 14 | 16 | ||
| 15 | const POLL_INTERVAL_MS = 1_000; | 17 | const POLL_INTERVAL_MS = 1_000; |
| 16 | 18 | ||
| 19 | +// A comfortable reading pace for the reveal, and the backlog past which it | ||
| 20 | +// stops pacing and catches up: a rule-based answer often lands whole in the | ||
| 21 | +// `done` event, and nobody should wait out an animation to read it. | ||
| 22 | +const REVEAL_CHARS_PER_SECOND = 90; | ||
| 23 | +const REVEAL_CATCH_UP_CHARS = 320; | ||
| 24 | +const REVEAL_CATCH_UP_FACTOR = 5; | ||
| 25 | + | ||
| 17 | export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean) => void }) { | 26 | export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean) => void }) { |
| 18 | const t = useT(); | 27 | const t = useT(); |
| 28 | + const navigate = useNavigate(); | ||
| 19 | const { locale } = usePreferences(); | 29 | const { locale } = usePreferences(); |
| 20 | const [draft, setDraft] = createSignal(""); | 30 | const [draft, setDraft] = createSignal(""); |
| 21 | const [messages, setMessages] = createSignal<PanelMessage[]>([]); | 31 | const [messages, setMessages] = createSignal<PanelMessage[]>([]); |
| @@ -30,6 +40,52 @@ export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean | |||
| 30 | window.setTimeout(() => setCopiedId((current) => (current === message.id ? undefined : current)), 1_500); | 40 | window.setTimeout(() => setCopiedId((current) => (current === message.id ? undefined : current)), 1_500); |
| 31 | }; | 41 | }; |
| 32 | 42 | ||
| 43 | + // Answers arrive either as stream deltas or whole in the `done` event, and | ||
| 44 | + // both used to appear in one jump. The reveal walks a character count over | ||
| 45 | + // whatever content the answer has so far, so a streamed answer types itself | ||
| 46 | + // and a whole one is still read at a human pace. Reduced motion skips it. | ||
| 47 | + const [typingId, setTypingId] = createSignal<string>(); | ||
| 48 | + const [typedCount, setTypedCount] = createSignal(0); | ||
| 49 | + let revealFrame: number | undefined; | ||
| 50 | + | ||
| 51 | + const prefersReducedMotion = () => | ||
| 52 | + typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches; | ||
| 53 | + | ||
| 54 | + const stopReveal = () => { | ||
| 55 | + if (revealFrame !== undefined) cancelAnimationFrame(revealFrame); | ||
| 56 | + revealFrame = undefined; | ||
| 57 | + setTypingId(undefined); | ||
| 58 | + }; | ||
| 59 | + | ||
| 60 | + const startReveal = (messageId: string) => { | ||
| 61 | + stopReveal(); | ||
| 62 | + if (prefersReducedMotion()) return; | ||
| 63 | + setTypingId(messageId); | ||
| 64 | + setTypedCount(0); | ||
| 65 | + let previous = performance.now(); | ||
| 66 | + const step = (now: number) => { | ||
| 67 | + const target = messages().find((item) => item.id === messageId); | ||
| 68 | + if (!target || typingId() !== messageId) return stopReveal(); | ||
| 69 | + const full = target.content.length; | ||
| 70 | + const behind = full - typedCount(); | ||
| 71 | + const speed = REVEAL_CHARS_PER_SECOND * (behind > REVEAL_CATCH_UP_CHARS ? REVEAL_CATCH_UP_FACTOR : 1); | ||
| 72 | + setTypedCount((count) => Math.min(full, count + ((now - previous) / 1_000) * speed)); | ||
| 73 | + previous = now; | ||
| 74 | + // Keep the frame running while the answer is still being written, even | ||
| 75 | + // once the text in hand is exhausted: the next delta extends it. | ||
| 76 | + if (typedCount() >= full && target.status !== "pending") return stopReveal(); | ||
| 77 | + revealFrame = requestAnimationFrame(step); | ||
| 78 | + }; | ||
| 79 | + revealFrame = requestAnimationFrame(step); | ||
| 80 | + }; | ||
| 81 | + | ||
| 82 | + /** How much of a message is on screen — the whole of it unless it is the one revealing. */ | ||
| 83 | + const visibleContent = (message: PanelMessage) => | ||
| 84 | + message.id === typingId() ? message.content.slice(0, Math.floor(typedCount())) : message.content; | ||
| 85 | + | ||
| 86 | + const isRevealing = (message: PanelMessage) => | ||
| 87 | + message.id === typingId() && (message.status === "pending" || Math.floor(typedCount()) < message.content.length); | ||
| 88 | + | ||
| 33 | // The transcript follows the newest message, but only while the reader is | 89 | // The transcript follows the newest message, but only while the reader is |
| 34 | // already at the bottom: scrolling up to re-read an earlier answer must not | 90 | // already at the bottom: scrolling up to re-read an earlier answer must not |
| 35 | // be yanked back down by the next streamed chunk. | 91 | // be yanked back down by the next streamed chunk. |
| @@ -41,6 +97,7 @@ export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean | |||
| 41 | }; | 97 | }; |
| 42 | createEffect(() => { | 98 | createEffect(() => { |
| 43 | const items = messages(); | 99 | const items = messages(); |
| 100 | + typedCount(); | ||
| 44 | if (!transcript || items.length === 0) return; | 101 | if (!transcript || items.length === 0) return; |
| 45 | const distance = transcript.scrollHeight - transcript.scrollTop - transcript.clientHeight; | 102 | const distance = transcript.scrollHeight - transcript.scrollTop - transcript.clientHeight; |
| 46 | const atBottom = distance <= NEAR_BOTTOM_PX; | 103 | const atBottom = distance <= NEAR_BOTTOM_PX; |
| @@ -58,8 +115,8 @@ export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean | |||
| 58 | }; | 115 | }; |
| 59 | const stopStream = () => { stream?.close(); stream = undefined; }; | 116 | const stopStream = () => { stream?.close(); stream = undefined; }; |
| 60 | const loadThreads = async () => { try { setThreads((await getChatbotThreads({ limit: 100 })).items); } catch { /* history is non-blocking */ } }; | 117 | const loadThreads = async () => { try { setThreads((await getChatbotThreads({ limit: 100 })).items); } catch { /* history is non-blocking */ } }; |
| 61 | - const openThread = async (id: string) => { stopPolling(); stopStream(); setThreadId(id); setMessages((await getChatbotThreadMessages(id, { limit: 500 })).items); }; | 118 | + const openThread = async (id: string) => { stopPolling(); stopStream(); stopReveal(); setThreadId(id); setMessages((await getChatbotThreadMessages(id, { limit: 500 })).items); }; |
| 62 | - const createThread = () => { stopPolling(); stopStream(); setThreadId(undefined); setMessages([]); }; | 119 | + const createThread = () => { stopPolling(); stopStream(); stopReveal(); setThreadId(undefined); setMessages([]); }; |
| 63 | 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(); } }; | 120 | 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(); } }; |
| 64 | 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(); }; | 121 | 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(); }; |
| 65 | createEffect(() => { if (props.open) void loadThreads(); }); | 122 | createEffect(() => { if (props.open) void loadThreads(); }); |
| @@ -97,7 +154,7 @@ export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean | |||
| 97 | source.onerror = () => { stopStream(); poll(activeThreadId, messageId); }; | 154 | source.onerror = () => { stopStream(); poll(activeThreadId, messageId); }; |
| 98 | }; | 155 | }; |
| 99 | 156 | ||
| 100 | - onCleanup(() => { stopPolling(); stopStream(); }); | 157 | + onCleanup(() => { stopPolling(); stopStream(); stopReveal(); }); |
| 101 | 158 | ||
| 102 | const send = async (override?: string) => { | 159 | const send = async (override?: string) => { |
| 103 | // A suggestion chip sends its own text without ever touching the draft. | 160 | // 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 | |||
| 127 | completed_at: null, | 184 | completed_at: null, |
| 128 | }, | 185 | }, |
| 129 | ]); | 186 | ]); |
| 187 | + startReveal(accepted.message_id); | ||
| 130 | streamAnswer(activeThreadId, accepted.message_id); | 188 | streamAnswer(activeThreadId, accepted.message_id); |
| 131 | void loadThreads(); | 189 | void loadThreads(); |
| 132 | } catch (error) { | 190 | } catch (error) { |
| @@ -190,23 +248,52 @@ export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean | |||
| 190 | <For each={messages()}> | 248 | <For each={messages()}> |
| 191 | {(message) => ( | 249 | {(message) => ( |
| 192 | <div class={message.role === "user" ? "ml-8 rounded-lg rounded-br-sm bg-primary px-3.5 py-2.5 text-sm text-primary-foreground" : "mr-6 rounded-lg rounded-bl-sm border border-border bg-card px-3.5 py-2.5 text-sm text-foreground shadow-sm"}> | 250 | <div class={message.role === "user" ? "ml-8 rounded-lg rounded-br-sm bg-primary px-3.5 py-2.5 text-sm text-primary-foreground" : "mr-6 rounded-lg rounded-bl-sm border border-border bg-card px-3.5 py-2.5 text-sm text-foreground shadow-sm"}> |
| 193 | - <Show when={message.role === "assistant" && message.status === "pending"} fallback={ | 251 | + <Switch> |
| 194 | - <Show when={message.role === "assistant" && message.status === "failed" && !message.content} fallback={ | 252 | + <Match when={message.role === "user"}> |
| 195 | - <Show when={message.role === "assistant"} fallback={<p class="whitespace-pre-wrap leading-6">{message.content}</p>}> | 253 | + <p class="whitespace-pre-wrap leading-6">{message.content}</p> |
| 196 | - <CelebiMarkdown text={message.content} /> | 254 | + </Match> |
| 197 | - </Show> | 255 | + <Match when={message.status === "failed" && !message.content}> |
| 198 | - }> | ||
| 199 | <p class="whitespace-pre-wrap leading-6">{failureMessage(message.error_code)}</p> | 256 | <p class="whitespace-pre-wrap leading-6">{failureMessage(message.error_code)}</p> |
| 200 | - </Show> | 257 | + </Match> |
| 201 | - }> | 258 | + {/* The label stands in only until the first characters land; |
| 202 | - <span class="flex items-center gap-2 text-muted-foreground"><IconBotSquare class="h-4 w-4 text-primary" /><span class="animate-pulse"><CelebiThinkingLabel /></span></span> | 259 | + an answer that is still being written keeps typing. */} |
| 203 | - </Show> | 260 | + <Match when={message.status === "pending" && !visibleContent(message)}> |
| 261 | + <span class="flex items-center gap-2 text-muted-foreground"><IconBotSquare class="h-4 w-4 text-primary" /><span class="animate-pulse"><CelebiThinkingLabel /></span></span> | ||
| 262 | + </Match> | ||
| 263 | + <Match when={true}> | ||
| 264 | + <CelebiMarkdown text={visibleContent(message)} /> | ||
| 265 | + <Show when={isRevealing(message)}> | ||
| 266 | + <span class="ml-1 inline-block h-3.5 w-0.5 animate-pulse rounded-full bg-primary align-middle" aria-hidden="true" /> | ||
| 267 | + <button | ||
| 268 | + type="button" | ||
| 269 | + class="mt-2 block text-xs text-muted-foreground underline-offset-2 hover:text-foreground hover:underline" | ||
| 270 | + onClick={stopReveal} | ||
| 271 | + > | ||
| 272 | + {t("ai.skipTyping")} | ||
| 273 | + </button> | ||
| 274 | + </Show> | ||
| 275 | + </Match> | ||
| 276 | + </Switch> | ||
| 204 | <Show when={message.role === "assistant" && message.status === "failed"}> | 277 | <Show when={message.role === "assistant" && message.status === "failed"}> |
| 205 | <span class="mt-2 flex items-center gap-1.5 text-xs text-destructive"><IconAlert class="h-3.5 w-3.5" />{failureMessage(message.error_code)}</span> | 278 | <span class="mt-2 flex items-center gap-1.5 text-xs text-destructive"><IconAlert class="h-3.5 w-3.5" />{failureMessage(message.error_code)}</span> |
| 206 | </Show> | 279 | </Show> |
| 207 | <Show when={message.role === "assistant" && message.truncated}> | 280 | <Show when={message.role === "assistant" && message.truncated}> |
| 208 | <p class="mt-2 text-xs text-muted-foreground">{locale() === "tr" ? "Yanıt uzunluk sınırında kısaltıldı." : "Response was shortened at the configured limit."}</p> | 281 | <p class="mt-2 text-xs text-muted-foreground">{locale() === "tr" ? "Yanıt uzunluk sınırında kısaltıldı." : "Response was shortened at the configured limit."}</p> |
| 209 | </Show> | 282 | </Show> |
| 283 | + <Show when={message.role === "assistant" && message.status === "complete" && !isRevealing(message)}> | ||
| 284 | + <CelebiReplyActions | ||
| 285 | + navigation={message.navigation} | ||
| 286 | + suggestions={message.suggestions} | ||
| 287 | + onNavigate={(route) => { | ||
| 288 | + props.onOpenChange(false); | ||
| 289 | + // The route is checked in celebi-route.ts, but it is a | ||
| 290 | + // runtime string either way — the router's typed table | ||
| 291 | + // cannot describe it. | ||
| 292 | + void navigate({ to: route as never }); | ||
| 293 | + }} | ||
| 294 | + onPick={(text) => void send(text)} | ||
| 295 | + /> | ||
| 296 | + </Show> | ||
| 210 | <Show when={message.role === "assistant" && message.status === "complete"}> | 297 | <Show when={message.role === "assistant" && message.status === "complete"}> |
| 211 | <button | 298 | <button |
| 212 | type="button" | 299 | type="button" |
src/components/layout/celebi-reply-actions.test.tsxadded+50 -0
| @@ -0,0 +1,50 @@ | |||
| 1 | +import { render, screen } from "@solidjs/testing-library"; | ||
| 2 | +import { CelebiReplyActions } from "@/components/layout/celebi-reply-actions"; | ||
| 3 | +import { PreferencesProvider } from "@/stores/preferences-context"; | ||
| 4 | + | ||
| 5 | +const noop = () => {}; | ||
| 6 | + | ||
| 7 | +function mount(props: Parameters<typeof CelebiReplyActions>[0]) { | ||
| 8 | + return render(() => ( | ||
| 9 | + <PreferencesProvider> | ||
| 10 | + <CelebiReplyActions {...props} /> | ||
| 11 | + </PreferencesProvider> | ||
| 12 | + )); | ||
| 13 | +} | ||
| 14 | + | ||
| 15 | +test("renders nothing when the answer carries neither half", () => { | ||
| 16 | + const { container } = mount({ onNavigate: noop, onPick: noop }); | ||
| 17 | + expect(container.textContent).toBe(""); | ||
| 18 | +}); | ||
| 19 | + | ||
| 20 | +test("navigates with the route the answer offered", () => { | ||
| 21 | + const routes: string[] = []; | ||
| 22 | + mount({ | ||
| 23 | + navigation: { route: "/exams", label: "Sınavlar" }, | ||
| 24 | + onNavigate: (route) => routes.push(route), | ||
| 25 | + onPick: noop, | ||
| 26 | + }); | ||
| 27 | + screen.getByText("Sınavlar").click(); | ||
| 28 | + expect(routes).toEqual(["/exams"]); | ||
| 29 | +}); | ||
| 30 | + | ||
| 31 | +test("drops a navigation that would leave the app", () => { | ||
| 32 | + mount({ | ||
| 33 | + navigation: { route: "//evil.example", label: "Sınavlar" }, | ||
| 34 | + onNavigate: noop, | ||
| 35 | + onPick: noop, | ||
| 36 | + }); | ||
| 37 | + expect(screen.queryByText("Sınavlar")).toBeNull(); | ||
| 38 | +}); | ||
| 39 | + | ||
| 40 | +test("asks the picked suggestion, and shows at most three", () => { | ||
| 41 | + const asked: string[] = []; | ||
| 42 | + mount({ | ||
| 43 | + suggestions: ["Bugün dersim var mı?", " ", "Sınavlarım ne zaman?", "Yoklamam nasıl?", "Fazlası"], | ||
| 44 | + onNavigate: noop, | ||
| 45 | + onPick: (text) => asked.push(text), | ||
| 46 | + }); | ||
| 47 | + expect(screen.queryByText("Fazlası")).toBeNull(); | ||
| 48 | + screen.getByText("Sınavlarım ne zaman?").click(); | ||
| 49 | + expect(asked).toEqual(["Sınavlarım ne zaman?"]); | ||
| 50 | +}); | ||
src/components/layout/celebi-reply-actions.tsxadded+66 -0
| @@ -0,0 +1,66 @@ | |||
| 1 | +import { For, Show } from "solid-js"; | ||
| 2 | +import type { ChatbotNavigation } from "@/api/chatbot"; | ||
| 3 | +import { IconChevronRight, IconSparkles } from "@/components/ui/icons"; | ||
| 4 | +import { safeCelebiRoute } from "@/lib/celebi-route"; | ||
| 5 | +import { useT } from "@/stores/preferences-context"; | ||
| 6 | + | ||
| 7 | +const MAX_SUGGESTIONS = 3; | ||
| 8 | + | ||
| 9 | +/** | ||
| 10 | + * The actionable half of an answer: the page it can take the user to, and the | ||
| 11 | + * follow-up questions it offers when it is not sure what was meant. Both come | ||
| 12 | + * from `chat.reply`; an answer that carries neither renders nothing at all. | ||
| 13 | + */ | ||
| 14 | +export function CelebiReplyActions(props: { | ||
| 15 | + navigation?: ChatbotNavigation | null; | ||
| 16 | + suggestions?: string[] | null; | ||
| 17 | + onNavigate: (route: string) => void; | ||
| 18 | + onPick: (text: string) => void; | ||
| 19 | +}) { | ||
| 20 | + const t = useT(); | ||
| 21 | + const route = () => safeCelebiRoute(props.navigation?.route); | ||
| 22 | + const label = () => props.navigation?.label?.trim() || t("ai.goTo"); | ||
| 23 | + const suggestions = () => | ||
| 24 | + (props.suggestions ?? []).map((text) => text.trim()).filter(Boolean).slice(0, MAX_SUGGESTIONS); | ||
| 25 | + | ||
| 26 | + return ( | ||
| 27 | + <Show when={route() || suggestions().length > 0}> | ||
| 28 | + <div class="mt-3 space-y-2 border-t border-border/60 pt-2.5"> | ||
| 29 | + <Show when={route()}> | ||
| 30 | + {(target) => ( | ||
| 31 | + <button | ||
| 32 | + type="button" | ||
| 33 | + class="inline-flex max-w-full items-center gap-1.5 rounded-lg border border-primary/40 bg-primary/10 px-2.5 py-1.5 text-xs font-medium text-foreground transition-colors hover:bg-primary/20 focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-primary/50" | ||
| 34 | + onClick={() => props.onNavigate(target())} | ||
| 35 | + > | ||
| 36 | + <span class="truncate">{label()}</span> | ||
| 37 | + <IconChevronRight class="h-3.5 w-3.5 shrink-0" /> | ||
| 38 | + </button> | ||
| 39 | + )} | ||
| 40 | + </Show> | ||
| 41 | + | ||
| 42 | + <Show when={suggestions().length > 0}> | ||
| 43 | + <div class="space-y-1.5"> | ||
| 44 | + <p class="flex items-center gap-1.5 text-[11px] font-medium text-muted-foreground"> | ||
| 45 | + <IconSparkles class="h-3 w-3" /> | ||
| 46 | + {t("ai.didYouMean")} | ||
| 47 | + </p> | ||
| 48 | + <div class="flex flex-wrap gap-1.5"> | ||
| 49 | + <For each={suggestions()}> | ||
| 50 | + {(text) => ( | ||
| 51 | + <button | ||
| 52 | + type="button" | ||
| 53 | + class="max-w-full rounded-full border border-border bg-card px-2.5 py-1 text-left text-xs leading-5 text-foreground transition-colors hover:border-primary/40 hover:bg-muted focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-primary/50" | ||
| 54 | + onClick={() => props.onPick(text)} | ||
| 55 | + > | ||
| 56 | + {text} | ||
| 57 | + </button> | ||
| 58 | + )} | ||
| 59 | + </For> | ||
| 60 | + </div> | ||
| 61 | + </div> | ||
| 62 | + </Show> | ||
| 63 | + </div> | ||
| 64 | + </Show> | ||
| 65 | + ); | ||
| 66 | +} | ||
src/i18n/messages.tsmodified+9 -0
| @@ -28,6 +28,9 @@ export type MessageKey = | |||
| 28 | | "ai.suggestParent2" | 28 | | "ai.suggestParent2" |
| 29 | | "ai.suggestParent3" | 29 | | "ai.suggestParent3" |
| 30 | | "ai.suggestParent4" | 30 | | "ai.suggestParent4" |
| 31 | + | "ai.goTo" | ||
| 32 | + | "ai.didYouMean" | ||
| 33 | + | "ai.skipTyping" | ||
| 31 | | "nav.today" | 34 | | "nav.today" |
| 32 | | "nav.classes" | 35 | | "nav.classes" |
| 33 | | "nav.classGroups" | 36 | | "nav.classGroups" |
| @@ -1557,6 +1560,9 @@ const en: Dict = { | |||
| 1557 | "ai.suggestParent2": "Which exams does my child have soon?", | 1560 | "ai.suggestParent2": "Which exams does my child have soon?", |
| 1558 | "ai.suggestParent3": "How is my child's attendance this term?", | 1561 | "ai.suggestParent3": "How is my child's attendance this term?", |
| 1559 | "ai.suggestParent4": "What is on this week's meal menu?", | 1562 | "ai.suggestParent4": "What is on this week's meal menu?", |
| 1563 | + "ai.goTo": "Go to the page", | ||
| 1564 | + "ai.didYouMean": "Did you mean one of these?", | ||
| 1565 | + "ai.skipTyping": "Show the whole answer", | ||
| 1560 | "nav.today": "Today", | 1566 | "nav.today": "Today", |
| 1561 | "nav.classes": "Education", | 1567 | "nav.classes": "Education", |
| 1562 | "nav.classGroups": "Classes", | 1568 | "nav.classGroups": "Classes", |
| @@ -3097,6 +3103,9 @@ const tr: Dict = { | |||
| 3097 | "ai.suggestParent2": "Çocuğumun yaklaşan sınavları neler?", | 3103 | "ai.suggestParent2": "Çocuğumun yaklaşan sınavları neler?", |
| 3098 | "ai.suggestParent3": "Çocuğumun bu dönem devamsızlığı nasıl?", | 3104 | "ai.suggestParent3": "Çocuğumun bu dönem devamsızlığı nasıl?", |
| 3099 | "ai.suggestParent4": "Bu haftanın yemek menüsünde ne var?", | 3105 | "ai.suggestParent4": "Bu haftanın yemek menüsünde ne var?", |
| 3106 | + "ai.goTo": "Sayfaya git", | ||
| 3107 | + "ai.didYouMean": "Bunu mu demek istedin?", | ||
| 3108 | + "ai.skipTyping": "Cevabın tamamını göster", | ||
| 3100 | "nav.today": "Bugün", | 3109 | "nav.today": "Bugün", |
| 3101 | "nav.classes": "Eğitim", | 3110 | "nav.classes": "Eğitim", |
| 3102 | "nav.classGroups": "Şubeler", | 3111 | "nav.classGroups": "Şubeler", |
src/lib/celebi-route.test.tsadded+26 -0
| @@ -0,0 +1,26 @@ | |||
| 1 | +import { describe, expect, it } from "vitest"; | ||
| 2 | +import { safeCelebiRoute } from "./celebi-route"; | ||
| 3 | + | ||
| 4 | +describe("safeCelebiRoute", () => { | ||
| 5 | + it("keeps an in-app path, trimmed", () => { | ||
| 6 | + expect(safeCelebiRoute("/exams")).toBe("/exams"); | ||
| 7 | + expect(safeCelebiRoute(" /management/classes/abc ")).toBe("/management/classes/abc"); | ||
| 8 | + expect(safeCelebiRoute("/calendar?view=week")).toBe("/calendar?view=week"); | ||
| 9 | + }); | ||
| 10 | + | ||
| 11 | + it("rejects anything that could leave the app", () => { | ||
| 12 | + expect(safeCelebiRoute("//evil.example/phish")).toBeNull(); | ||
| 13 | + expect(safeCelebiRoute("/\\evil.example")).toBeNull(); | ||
| 14 | + expect(safeCelebiRoute("https://evil.example")).toBeNull(); | ||
| 15 | + expect(safeCelebiRoute("javascript:alert(1)")).toBeNull(); | ||
| 16 | + expect(safeCelebiRoute("exams")).toBeNull(); | ||
| 17 | + }); | ||
| 18 | + | ||
| 19 | + it("rejects a path that is not one", () => { | ||
| 20 | + expect(safeCelebiRoute("/exams and more")).toBeNull(); | ||
| 21 | + expect(safeCelebiRoute("/exams\nHost: evil")).toBeNull(); | ||
| 22 | + expect(safeCelebiRoute("")).toBeNull(); | ||
| 23 | + expect(safeCelebiRoute(null)).toBeNull(); | ||
| 24 | + expect(safeCelebiRoute(undefined)).toBeNull(); | ||
| 25 | + }); | ||
| 26 | +}); | ||
src/lib/celebi-route.tsadded+16 -0
| @@ -0,0 +1,16 @@ | |||
| 1 | +/** | ||
| 2 | + * An answer may offer to take the user somewhere. The route arrives from the | ||
| 3 | + * backend, so it is treated as data: only an in-app absolute path is accepted, | ||
| 4 | + * which keeps `//evil.example` (protocol-relative), `javascript:` and every | ||
| 5 | + * other off-site target from ever reaching the router. | ||
| 6 | + */ | ||
| 7 | +export function safeCelebiRoute(route: string | null | undefined): string | null { | ||
| 8 | + if (typeof route !== "string") return null; | ||
| 9 | + const trimmed = route.trim(); | ||
| 10 | + if (!trimmed.startsWith("/")) return null; | ||
| 11 | + if (trimmed.startsWith("//") || trimmed.startsWith("/\\")) return null; | ||
| 12 | + // Printable ASCII without spaces: a route is a path, and anything else in it | ||
| 13 | + // (control characters, line breaks) means it is not one. | ||
| 14 | + if (!/^[\x21-\x7e]+$/.test(trimmed)) return null; | ||
| 15 | + return trimmed; | ||
| 16 | +} | ||
vitest.config.tsmodified+5 -1
| @@ -26,7 +26,11 @@ export default defineConfig({ | |||
| 26 | }, | 26 | }, |
| 27 | }, | 27 | }, |
| 28 | { | 28 | { |
| 29 | - plugins: [solid()], | 29 | + // `hot: false`: the plugin otherwise injects solid-refresh's virtual |
| 30 | + // module, and vitest hands node the unresolvable `file:///@solid-refresh` | ||
| 31 | + // specifier — every *.test.tsx file failed to load on that alone. There | ||
| 32 | + // is no HMR in a test run for it to serve. | ||
| 33 | + plugins: [solid({ hot: false })], | ||
| 30 | // "development"/"browser" so solid-js resolves to its client build once — | 34 | // "development"/"browser" so solid-js resolves to its client build once — |
| 31 | // a dual-loaded solid-js gives components a different reactive graph. | 35 | // a dual-loaded solid-js gives components a different reactive graph. |
| 32 | resolve: { alias, conditions: ["development", "browser"] }, | 36 | resolve: { alias, conditions: ["development", "browser"] }, |