hezarfen_frontend
Clone
https://git.tahinli.com/archive/hezarfen_frontend.git
0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits
| 1 | import { For, Show, createEffect, createSignal, on, onCleanup } from "solid-js"; |
| 2 | import { formatApiError } from "@/api/client"; |
| 3 | import type { RagMessage, RagThread } from "@/api/client"; |
| 4 | import { |
| 5 | deleteRagThreadById, |
| 6 | getRagMessageById, |
| 7 | getRagThreadMessages, |
| 8 | patchRagThreadById, |
| 9 | postRagMessage, |
| 10 | postRagThread, |
| 11 | ragStreamUrl, |
| 12 | } from "@/api/rag"; |
| 13 | import { RagComposer } from "@/components/rag/rag-composer"; |
| 14 | import { ragCopy } from "@/components/rag/rag-copy"; |
| 15 | import { RagMessageRow } from "@/components/rag/rag-message-row"; |
| 16 | import { RagStudyActions } from "@/components/rag/rag-study-actions"; |
| 17 | import { RagStudyWelcome } from "@/components/rag/rag-study-welcome"; |
| 18 | import { RagThreadList } from "@/components/rag/rag-thread-list"; |
| 19 | import { Alert } from "@/components/ui/alert"; |
| 20 | import { Button } from "@/components/ui/button"; |
| 21 | import { ConfirmDialog } from "@/components/ui/confirm-dialog"; |
| 22 | import { IconChevronDown, IconPlus } from "@/components/ui/icons"; |
| 23 | import { cn } from "@/lib/cn"; |
| 24 | import { scopeFromCitations } from "@/lib/rag-study-scope"; |
| 25 | import { usePreferences } from "@/stores/preferences-context"; |
| 26 | |
| 27 | const POLL_INTERVAL_MS = 2000; |
| 28 | |
| 29 | /** |
| 30 | * The AI hub's Study tab: chat over the course material the account may |
| 31 | * read (`/rag/*`), every answer with its sources, and under each sourced |
| 32 | * answer a way to summarize or practise exactly that range. Çelebi keeps its |
| 33 | * own general chat on `/chatbot`; this is the grounded one. |
| 34 | */ |
| 35 | export function RagStudyPanel() { |
| 36 | const { locale } = usePreferences(); |
| 37 | const copy = () => ragCopy(locale()); |
| 38 | const [threadId, setThreadId] = createSignal<string | undefined>(); |
| 39 | const [activeThread, setActiveThread] = createSignal<RagThread>(); |
| 40 | const [threadsVersion, setThreadsVersion] = createSignal(0); |
| 41 | const [messages, setMessages] = createSignal<RagMessage[]>([]); |
| 42 | const [draft, setDraft] = createSignal(""); |
| 43 | const [sending, setSending] = createSignal(false); |
| 44 | const [error, setError] = createSignal(""); |
| 45 | const [studyUnavailable, setStudyUnavailable] = createSignal(false); |
| 46 | const [renaming, setRenaming] = createSignal<RagThread | null>(null); |
| 47 | const [removing, setRemoving] = createSignal<RagThread | null>(null); |
| 48 | |
| 49 | let pollTimer: number | undefined; |
| 50 | let stream: EventSource | undefined; |
| 51 | const stopPolling = () => { |
| 52 | if (pollTimer !== undefined) window.clearInterval(pollTimer); |
| 53 | pollTimer = undefined; |
| 54 | }; |
| 55 | const stopStream = () => { |
| 56 | stream?.close(); |
| 57 | stream = undefined; |
| 58 | }; |
| 59 | onCleanup(() => { |
| 60 | stopPolling(); |
| 61 | stopStream(); |
| 62 | }); |
| 63 | |
| 64 | const updateMessage = (message: RagMessage) => { |
| 65 | setMessages((items) => items.map((item) => (item.id === message.id ? message : item))); |
| 66 | if (message.status !== "pending") stopPolling(); |
| 67 | }; |
| 68 | const poll = (activeThread: string, messageId: string) => { |
| 69 | stopPolling(); |
| 70 | const read = async () => { |
| 71 | try { |
| 72 | updateMessage(await getRagMessageById(activeThread, messageId)); |
| 73 | } catch { |
| 74 | // A transient poll failure does not turn an accepted turn into an error. |
| 75 | } |
| 76 | }; |
| 77 | void read(); |
| 78 | pollTimer = window.setInterval(() => void read(), POLL_INTERVAL_MS); |
| 79 | }; |
| 80 | // `done` carries the whole settled turn, citations included, so a late |
| 81 | // reader gets the sources too; any stream trouble falls back to polling. |
| 82 | const streamAnswer = (activeThread: string, messageId: string) => { |
| 83 | stopStream(); |
| 84 | const source = new EventSource(ragStreamUrl(activeThread, messageId), { withCredentials: true }); |
| 85 | stream = source; |
| 86 | source.addEventListener("delta", (event) => { |
| 87 | try { |
| 88 | const data = JSON.parse((event as MessageEvent).data) as { text?: unknown }; |
| 89 | if (typeof data.text === "string") { |
| 90 | const text = data.text; |
| 91 | setMessages((items) => items.map((item) => (item.id === messageId ? { ...item, content: item.content + text } : item))); |
| 92 | } |
| 93 | } catch { |
| 94 | // A malformed chunk is skipped; `done` settles the turn anyway. |
| 95 | } |
| 96 | }); |
| 97 | source.addEventListener("done", (event) => { |
| 98 | try { |
| 99 | updateMessage((JSON.parse((event as MessageEvent).data) as { message: RagMessage }).message); |
| 100 | } catch { |
| 101 | poll(activeThread, messageId); |
| 102 | } finally { |
| 103 | stopStream(); |
| 104 | setThreadsVersion((version) => version + 1); |
| 105 | } |
| 106 | }); |
| 107 | source.onerror = () => { |
| 108 | stopStream(); |
| 109 | poll(activeThread, messageId); |
| 110 | }; |
| 111 | }; |
| 112 | |
| 113 | const openThread = async (thread: RagThread) => { |
| 114 | stopPolling(); |
| 115 | stopStream(); |
| 116 | setError(""); |
| 117 | setThreadId(thread.id); |
| 118 | setActiveThread(thread); |
| 119 | try { |
| 120 | setMessages((await getRagThreadMessages(thread.id, { limit: 500 })).items); |
| 121 | } catch (err) { |
| 122 | setError(formatApiError(err)); |
| 123 | } |
| 124 | }; |
| 125 | const newThread = () => { |
| 126 | stopPolling(); |
| 127 | stopStream(); |
| 128 | setError(""); |
| 129 | setThreadId(undefined); |
| 130 | setActiveThread(undefined); |
| 131 | setMessages([]); |
| 132 | }; |
| 133 | |
| 134 | const send = async () => { |
| 135 | const content = draft().trim(); |
| 136 | if (!content || sending()) return; |
| 137 | setSending(true); |
| 138 | setError(""); |
| 139 | setDraft(""); |
| 140 | const now = Date.now(); |
| 141 | setMessages((items) => [ |
| 142 | ...items, |
| 143 | { id: `local-${now}`, thread_id: threadId() ?? "", role: "user", status: "complete", content, abstained: false, reason: "", citations: [], created_at: now }, |
| 144 | ]); |
| 145 | try { |
| 146 | const currentThread = threadId(); |
| 147 | const createdThread = currentThread ? undefined : await postRagThread(); |
| 148 | const resolvedThreadId = currentThread ?? createdThread!.id; |
| 149 | if (createdThread) setActiveThread(createdThread); |
| 150 | setThreadId(resolvedThreadId); |
| 151 | const accepted = await postRagMessage(resolvedThreadId, content); |
| 152 | setMessages((items) => [ |
| 153 | ...items, |
| 154 | { id: accepted.message_id, thread_id: resolvedThreadId, role: "assistant", status: "pending", content: "", abstained: false, reason: "", citations: [], created_at: Date.now() }, |
| 155 | ]); |
| 156 | streamAnswer(resolvedThreadId, accepted.message_id); |
| 157 | setThreadsVersion((version) => version + 1); |
| 158 | } catch (err) { |
| 159 | setError(formatApiError(err)); |
| 160 | setDraft(content); |
| 161 | } finally { |
| 162 | setSending(false); |
| 163 | } |
| 164 | }; |
| 165 | |
| 166 | // The transcript follows the newest turn only while the reader is pinned to |
| 167 | // the bottom. Any upward scroll unpins at once — a distance threshold alone |
| 168 | // lost to a streamed answer that grows every frame and kept dragging the |
| 169 | // reader back down. Content that lands while unpinned raises the pill below |
| 170 | // instead of yanking the view. |
| 171 | let scroller: HTMLDivElement | undefined; |
| 172 | const NEAR_BOTTOM_PX = 64; |
| 173 | const [pinned, setPinned] = createSignal(true); |
| 174 | const [unread, setUnread] = createSignal(false); |
| 175 | let lastScrollTop = 0; |
| 176 | const scrollToLatest = () => { |
| 177 | if (!scroller) return; |
| 178 | setPinned(true); |
| 179 | setUnread(false); |
| 180 | scroller.scrollTo({ top: scroller.scrollHeight, behavior: "smooth" }); |
| 181 | }; |
| 182 | const handleTranscriptScroll = () => { |
| 183 | if (!scroller) return; |
| 184 | const top = scroller.scrollTop; |
| 185 | const distance = scroller.scrollHeight - top - scroller.clientHeight; |
| 186 | if (top < lastScrollTop - 1 && distance > 1) setPinned(false); |
| 187 | else if (distance <= NEAR_BOTTOM_PX) { |
| 188 | setPinned(true); |
| 189 | setUnread(false); |
| 190 | } |
| 191 | lastScrollTop = top; |
| 192 | }; |
| 193 | createEffect( |
| 194 | on( |
| 195 | () => { |
| 196 | const items = messages(); |
| 197 | return `${items.length}:${items[items.length - 1]?.content.length ?? 0}`; |
| 198 | }, |
| 199 | () => { |
| 200 | const el = scroller; |
| 201 | if (!el) return; |
| 202 | if (!pinned()) { setUnread(true); return; } |
| 203 | queueMicrotask(() => { |
| 204 | el.scrollTop = el.scrollHeight; |
| 205 | lastScrollTop = el.scrollTop; |
| 206 | }); |
| 207 | }, |
| 208 | { defer: true }, |
| 209 | ), |
| 210 | ); |
| 211 | |
| 212 | /** Re-ask the question an answer replies to, through the same send pipeline. */ |
| 213 | const retry = (question: string) => { |
| 214 | if (sending()) return; |
| 215 | setDraft(question); |
| 216 | void send(); |
| 217 | }; |
| 218 | |
| 219 | /** The user turn an answer replies to, used as the study range's label. */ |
| 220 | const questionBefore = (index: number) => { |
| 221 | for (let i = index - 1; i >= 0; i -= 1) if (messages()[i]?.role === "user") return messages()[i]!.content; |
| 222 | return undefined; |
| 223 | }; |
| 224 | |
| 225 | return ( |
| 226 | <div class="grid min-h-[calc(100dvh-10rem)] gap-4 lg:h-[calc(100dvh-10rem)] lg:grid-cols-[18rem_minmax(0,1fr)]"> |
| 227 | <aside class="flex h-full min-h-0 flex-col gap-3 rounded-xl border border-border-line bg-surface-base p-3 shadow-xs"> |
| 228 | <div class="flex items-center justify-between gap-2"> |
| 229 | <h2 class="text-sm font-semibold text-text-strong">{copy().history}</h2> |
| 230 | <Button type="button" size="sm" class="h-8 rounded-lg" disabled={!threadId() && messages().length === 0} onClick={newThread}> |
| 231 | <IconPlus class="h-4 w-4" /> |
| 232 | {copy().newThread} |
| 233 | </Button> |
| 234 | </div> |
| 235 | <RagThreadList |
| 236 | activeId={threadId()} |
| 237 | version={threadsVersion()} |
| 238 | locale={locale()} |
| 239 | labels={copy()} |
| 240 | onOpen={(thread) => void openThread(thread)} |
| 241 | onRename={setRenaming} |
| 242 | onRemove={setRemoving} |
| 243 | /> |
| 244 | </aside> |
| 245 | |
| 246 | {/* No card, no header strip: the transcript sits on the page the way a |
| 247 | chat does. The conversation's own actions live on its row in the |
| 248 | sidebar, which is where they were already duplicated. */} |
| 249 | <section class="flex h-full min-h-0 flex-col" aria-label={copy().title}> |
| 250 | <Show when={error()}> |
| 251 | <div class="mx-auto w-full max-w-3xl px-4 pt-1 sm:px-6"> |
| 252 | <Alert variant="destructive">{error()}</Alert> |
| 253 | </div> |
| 254 | </Show> |
| 255 | <div class="relative min-h-0 flex-1"> |
| 256 | <div ref={scroller} onScroll={handleTranscriptScroll} class="h-full overflow-y-auto px-4 py-5 sm:px-6" aria-live="polite"> |
| 257 | <div class="mx-auto w-full max-w-3xl space-y-6"> |
| 258 | <Show |
| 259 | when={messages().length > 0} |
| 260 | fallback={ |
| 261 | // The landing screen centres the mark and the composer instead of |
| 262 | // stranding the composer at the bottom of an empty page. |
| 263 | <div class="flex min-h-[60vh] flex-col justify-center"> |
| 264 | <RagStudyWelcome title={copy().emptyChat} hint={copy().emptyChatHint} /> |
| 265 | <RagComposer |
| 266 | value={draft()} |
| 267 | placeholder={copy().placeholder} |
| 268 | sendLabel={copy().send} |
| 269 | hint={copy().composerHint} |
| 270 | disabled={sending()} |
| 271 | autofocus |
| 272 | class="px-0 sm:px-0" |
| 273 | onInput={setDraft} |
| 274 | onSubmit={() => void send()} |
| 275 | /> |
| 276 | </div> |
| 277 | } |
| 278 | > |
| 279 | <For each={messages()}> |
| 280 | {(message, index) => { |
| 281 | const scope = () => |
| 282 | message.role === "assistant" && message.status === "complete" && !message.abstained |
| 283 | ? scopeFromCitations(message.citations, questionBefore(index())) |
| 284 | : null; |
| 285 | const question = () => questionBefore(index()); |
| 286 | const retryable = () => |
| 287 | message.role === "assistant" && |
| 288 | index() === messages().length - 1 && |
| 289 | (message.status === "complete" || message.status === "failed") && |
| 290 | question() != null; |
| 291 | return ( |
| 292 | <RagMessageRow |
| 293 | message={message} |
| 294 | labels={copy()} |
| 295 | onRetry={retryable() ? () => retry(question()!) : undefined} |
| 296 | footer={ |
| 297 | <Show when={scope()}> |
| 298 | {(current) => ( |
| 299 | <RagStudyActions |
| 300 | scope={current()} |
| 301 | copy={copy()} |
| 302 | unavailable={studyUnavailable()} |
| 303 | onUnavailable={() => setStudyUnavailable(true)} |
| 304 | /> |
| 305 | )} |
| 306 | </Show> |
| 307 | } |
| 308 | /> |
| 309 | ); |
| 310 | }} |
| 311 | </For> |
| 312 | </Show> |
| 313 | </div> |
| 314 | </div> |
| 315 | <Show when={!pinned()}> |
| 316 | <button |
| 317 | type="button" |
| 318 | class={cn( |
| 319 | "absolute bottom-3 left-1/2 inline-flex h-8 -translate-x-1/2 items-center gap-1.5 rounded-full border px-3 text-xs font-medium shadow-md backdrop-blur transition-colors", |
| 320 | unread() |
| 321 | ? "border-primary bg-primary text-primary-foreground hover:bg-primary/90" |
| 322 | : "border-border bg-surface-base/95 text-foreground hover:bg-surface-overlay", |
| 323 | )} |
| 324 | onClick={scrollToLatest} |
| 325 | > |
| 326 | <IconChevronDown class="h-3.5 w-3.5" /> |
| 327 | {unread() ? copy().newMessages : copy().scrollToLatest} |
| 328 | </button> |
| 329 | </Show> |
| 330 | </div> |
| 331 | <Show when={messages().length > 0}> |
| 332 | <RagComposer |
| 333 | value={draft()} |
| 334 | placeholder={copy().placeholder} |
| 335 | sendLabel={copy().send} |
| 336 | hint={copy().composerHint} |
| 337 | disabled={sending()} |
| 338 | autofocus |
| 339 | class="pb-4" |
| 340 | onInput={setDraft} |
| 341 | onSubmit={() => void send()} |
| 342 | /> |
| 343 | </Show> |
| 344 | </section> |
| 345 | |
| 346 | <ConfirmDialog |
| 347 | open={renaming() != null} |
| 348 | onOpenChange={(open) => !open && setRenaming(null)} |
| 349 | title={copy().rename} |
| 350 | description={copy().renameHint} |
| 351 | summary={renaming()?.title || copy().untitled} |
| 352 | confirmLabel={copy().rename} |
| 353 | prompt={{ label: copy().renameLabel, placeholder: copy().renamePlaceholder, maxLength: 200, initialValue: renaming()?.title ?? "", singleLine: true }} |
| 354 | onConfirm={async (title) => { |
| 355 | const thread = renaming(); |
| 356 | if (!thread) return; |
| 357 | const nextTitle = title?.trim() || null; |
| 358 | await patchRagThreadById(thread.id, nextTitle); |
| 359 | if (activeThread()?.id === thread.id) setActiveThread({ ...activeThread()!, title: nextTitle }); |
| 360 | setThreadsVersion((version) => version + 1); |
| 361 | }} |
| 362 | /> |
| 363 | <ConfirmDialog |
| 364 | open={removing() != null} |
| 365 | onOpenChange={(open) => !open && setRemoving(null)} |
| 366 | title={copy().delete} |
| 367 | description={copy().deleteHint} |
| 368 | summary={removing()?.title || copy().untitled} |
| 369 | confirmLabel={copy().deleteConfirm} |
| 370 | variant="destructive" |
| 371 | onConfirm={async () => { |
| 372 | const thread = removing(); |
| 373 | if (!thread) return; |
| 374 | await deleteRagThreadById(thread.id); |
| 375 | if (threadId() === thread.id) newThread(); |
| 376 | setThreadsVersion((version) => version + 1); |
| 377 | }} |
| 378 | /> |
| 379 | </div> |
| 380 | ); |
| 381 | } |