hezarfen_frontend
Clone
https://git.tahinli.com/archive/hezarfen_frontend.git
0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits
| 1 | import { For, Show, createEffect, createSignal, on, onCleanup } from "solid-js"; |
| 2 | import { useNavigate, useParams } from "@tanstack/solid-router"; |
| 3 | import { formatApiError } from "@/api/client"; |
| 4 | import type { RagMessage, RagThread } from "@/api/client"; |
| 5 | import { |
| 6 | deleteRagThreadById, |
| 7 | getRagMessageById, |
| 8 | getRagThreadMessages, |
| 9 | patchRagThreadById, |
| 10 | postRagMessage, |
| 11 | postRagThread, |
| 12 | ragStreamUrl, |
| 13 | } from "@/api/rag"; |
| 14 | import { RagComposer } from "@/components/rag/rag-composer"; |
| 15 | import { ragCopy } from "@/components/rag/rag-copy"; |
| 16 | import { RagMessageRow } from "@/components/rag/rag-message-row"; |
| 17 | import { RagStudyActions } from "@/components/rag/rag-study-actions"; |
| 18 | import { RagStudyWelcome } from "@/components/rag/rag-study-welcome"; |
| 19 | import { RagThreadList } from "@/components/rag/rag-thread-list"; |
| 20 | import { Alert } from "@/components/ui/alert"; |
| 21 | import { ConfirmDialog } from "@/components/ui/confirm-dialog"; |
| 22 | import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; |
| 23 | import { IconChevronDown, IconEdit, IconMenu, IconPanelLeft, IconPlus, IconTrash, IconX } from "@/components/ui/icons"; |
| 24 | import { cn } from "@/lib/cn"; |
| 25 | import { scopeFromCitations } from "@/lib/rag-study-scope"; |
| 26 | import { useAuth } from "@/stores/auth-context"; |
| 27 | import { usePreferences } from "@/stores/preferences-context"; |
| 28 | import { suppressQuickActions } from "@/stores/quick-actions"; |
| 29 | |
| 30 | const POLL_INTERVAL_MS = 2000; |
| 31 | const COLLAPSED_KEY = "hezarfen.study.historyCollapsed"; |
| 32 | |
| 33 | /** |
| 34 | * The AI hub's Study tab: chat over the course material the account may |
| 35 | * read (`/rag/*`), every answer with its sources, and under each sourced |
| 36 | * answer a way to summarize or practise exactly that range. Çelebi keeps its |
| 37 | * own general chat on `/chatbot`; this is the grounded one. |
| 38 | */ |
| 39 | export function RagStudyPanel() { |
| 40 | // The page is a docked composer; the phone quick-action button would sit |
| 41 | // on its send button. |
| 42 | suppressQuickActions(); |
| 43 | const { locale } = usePreferences(); |
| 44 | const copy = () => ragCopy(locale()); |
| 45 | const [threadId, setThreadId] = createSignal<string | undefined>(); |
| 46 | const [activeThread, setActiveThread] = createSignal<RagThread>(); |
| 47 | const [threadsVersion, setThreadsVersion] = createSignal(0); |
| 48 | const [messages, setMessages] = createSignal<RagMessage[]>([]); |
| 49 | const [draft, setDraft] = createSignal(""); |
| 50 | const [sending, setSending] = createSignal(false); |
| 51 | const [error, setError] = createSignal(""); |
| 52 | const [studyUnavailable, setStudyUnavailable] = createSignal(false); |
| 53 | // An opened chat's transcript is on its way: without this the landing |
| 54 | // greeting flashed in its place until the messages arrived. |
| 55 | const [loadingThread, setLoadingThread] = createSignal(false); |
| 56 | const [renaming, setRenaming] = createSignal<RagThread | null>(null); |
| 57 | const [removing, setRemoving] = createSignal<RagThread | null>(null); |
| 58 | // Below lg the history is a drawer from the left edge, the way a chat app |
| 59 | // on a phone keeps its conversations one tap away without spending the |
| 60 | // screen on them. From lg it is the fixed column beside the transcript. |
| 61 | const [historyOpen, setHistoryOpen] = createSignal(false); |
| 62 | // From lg the history is a sidebar the reader can fold away, remembered on |
| 63 | // this device the way a chat app remembers its sidebar. |
| 64 | const [historyCollapsed, setHistoryCollapsed] = createSignal( |
| 65 | typeof localStorage !== "undefined" && localStorage.getItem(COLLAPSED_KEY) === "1", |
| 66 | ); |
| 67 | createEffect(() => { |
| 68 | if (typeof localStorage !== "undefined") localStorage.setItem(COLLAPSED_KEY, historyCollapsed() ? "1" : "0"); |
| 69 | }); |
| 70 | const auth = useAuth(); |
| 71 | // A chat lives at /ai/study/$threadId, the way Vibe opens one at |
| 72 | // /chat/<id>. This panel is the persistent parent of that route, so moving |
| 73 | // between chats never remounts the sidebar or cuts a streaming answer. |
| 74 | const navigate = useNavigate(); |
| 75 | const params = useParams({ strict: false }); |
| 76 | const routeThreadId = () => (params() as { threadId?: string }).threadId; |
| 77 | // The API has no single-thread read; titles come from the sidebar's list. |
| 78 | const [knownThreads, setKnownThreads] = createSignal<RagThread[]>([]); |
| 79 | const greeting = () => { |
| 80 | const hour = new Date().getHours(); |
| 81 | const base = hour < 12 ? copy().greetingMorning : hour < 18 ? copy().greetingAfternoon : copy().greetingEvening; |
| 82 | const user = auth.user(); |
| 83 | const name = user?.display_name?.trim() || user?.name?.trim(); |
| 84 | return name ? `${base}, ${name}` : base; |
| 85 | }; |
| 86 | createEffect(() => { |
| 87 | if (!historyOpen()) return; |
| 88 | const onKey = (event: KeyboardEvent) => { |
| 89 | if (event.key === "Escape") setHistoryOpen(false); |
| 90 | }; |
| 91 | window.addEventListener("keydown", onKey); |
| 92 | onCleanup(() => window.removeEventListener("keydown", onKey)); |
| 93 | }); |
| 94 | |
| 95 | let pollTimer: number | undefined; |
| 96 | let stream: EventSource | undefined; |
| 97 | const stopPolling = () => { |
| 98 | if (pollTimer !== undefined) window.clearInterval(pollTimer); |
| 99 | pollTimer = undefined; |
| 100 | }; |
| 101 | const stopStream = () => { |
| 102 | stream?.close(); |
| 103 | stream = undefined; |
| 104 | }; |
| 105 | onCleanup(() => { |
| 106 | stopPolling(); |
| 107 | stopStream(); |
| 108 | }); |
| 109 | |
| 110 | const updateMessage = (message: RagMessage) => { |
| 111 | setMessages((items) => items.map((item) => (item.id === message.id ? message : item))); |
| 112 | if (message.status !== "pending") stopPolling(); |
| 113 | }; |
| 114 | const poll = (activeThread: string, messageId: string) => { |
| 115 | stopPolling(); |
| 116 | const read = async () => { |
| 117 | try { |
| 118 | updateMessage(await getRagMessageById(activeThread, messageId)); |
| 119 | } catch { |
| 120 | // A transient poll failure does not turn an accepted turn into an error. |
| 121 | } |
| 122 | }; |
| 123 | void read(); |
| 124 | pollTimer = window.setInterval(() => void read(), POLL_INTERVAL_MS); |
| 125 | }; |
| 126 | // `done` carries the whole settled turn, citations included, so a late |
| 127 | // reader gets the sources too; any stream trouble falls back to polling. |
| 128 | const streamAnswer = (activeThread: string, messageId: string) => { |
| 129 | stopStream(); |
| 130 | const source = new EventSource(ragStreamUrl(activeThread, messageId), { withCredentials: true }); |
| 131 | stream = source; |
| 132 | source.addEventListener("delta", (event) => { |
| 133 | try { |
| 134 | const data = JSON.parse((event as MessageEvent).data) as { text?: unknown }; |
| 135 | if (typeof data.text === "string") { |
| 136 | const text = data.text; |
| 137 | setMessages((items) => items.map((item) => (item.id === messageId ? { ...item, content: item.content + text } : item))); |
| 138 | } |
| 139 | } catch { |
| 140 | // A malformed chunk is skipped; `done` settles the turn anyway. |
| 141 | } |
| 142 | }); |
| 143 | source.addEventListener("done", (event) => { |
| 144 | try { |
| 145 | updateMessage((JSON.parse((event as MessageEvent).data) as { message: RagMessage }).message); |
| 146 | } catch { |
| 147 | poll(activeThread, messageId); |
| 148 | } finally { |
| 149 | stopStream(); |
| 150 | setThreadsVersion((version) => version + 1); |
| 151 | } |
| 152 | }); |
| 153 | source.onerror = () => { |
| 154 | stopStream(); |
| 155 | poll(activeThread, messageId); |
| 156 | }; |
| 157 | }; |
| 158 | |
| 159 | const loadThread = async (id: string) => { |
| 160 | stopPolling(); |
| 161 | stopStream(); |
| 162 | setError(""); |
| 163 | setThreadId(id); |
| 164 | setActiveThread(knownThreads().find((thread) => thread.id === id)); |
| 165 | setMessages([]); |
| 166 | setLoadingThread(true); |
| 167 | try { |
| 168 | const page = await getRagThreadMessages(id, { limit: 500 }); |
| 169 | if (threadId() === id) setMessages(page.items); |
| 170 | } catch (err) { |
| 171 | if (threadId() === id) setError(formatApiError(err)); |
| 172 | } finally { |
| 173 | if (threadId() === id) setLoadingThread(false); |
| 174 | } |
| 175 | }; |
| 176 | const resetThread = () => { |
| 177 | stopPolling(); |
| 178 | stopStream(); |
| 179 | setError(""); |
| 180 | setThreadId(undefined); |
| 181 | setActiveThread(undefined); |
| 182 | setMessages([]); |
| 183 | setLoadingThread(false); |
| 184 | }; |
| 185 | // The URL is the source of truth for which chat is open. A chat this panel |
| 186 | // just created is already open when its URL lands, so it is not reloaded. |
| 187 | createEffect( |
| 188 | on(routeThreadId, (id) => { |
| 189 | if (id === threadId()) return; |
| 190 | if (id) void loadThread(id); |
| 191 | else resetThread(); |
| 192 | }), |
| 193 | ); |
| 194 | createEffect(() => { |
| 195 | const id = threadId(); |
| 196 | if (!id || activeThread()?.id === id) return; |
| 197 | const known = knownThreads().find((thread) => thread.id === id); |
| 198 | if (known) setActiveThread(known); |
| 199 | }); |
| 200 | const openThread = (thread: RagThread) => { |
| 201 | setActiveThread(thread); |
| 202 | void navigate({ to: "/ai/study/$threadId", params: { threadId: thread.id } }); |
| 203 | }; |
| 204 | const newThread = () => { |
| 205 | void navigate({ to: "/ai/study" }); |
| 206 | }; |
| 207 | |
| 208 | const send = async () => { |
| 209 | const content = draft().trim(); |
| 210 | if (!content || sending()) return; |
| 211 | setSending(true); |
| 212 | setError(""); |
| 213 | setDraft(""); |
| 214 | const now = Date.now(); |
| 215 | setMessages((items) => [ |
| 216 | ...items, |
| 217 | { id: `local-${now}`, thread_id: threadId() ?? "", role: "user", status: "complete", content, abstained: false, reason: "", citations: [], created_at: now }, |
| 218 | ]); |
| 219 | try { |
| 220 | const currentThread = threadId(); |
| 221 | const createdThread = currentThread ? undefined : await postRagThread(); |
| 222 | const resolvedThreadId = currentThread ?? createdThread!.id; |
| 223 | if (createdThread) setActiveThread(createdThread); |
| 224 | setThreadId(resolvedThreadId); |
| 225 | if (createdThread) void navigate({ to: "/ai/study/$threadId", params: { threadId: resolvedThreadId }, replace: true }); |
| 226 | const accepted = await postRagMessage(resolvedThreadId, content); |
| 227 | setMessages((items) => [ |
| 228 | ...items, |
| 229 | { id: accepted.message_id, thread_id: resolvedThreadId, role: "assistant", status: "pending", content: "", abstained: false, reason: "", citations: [], created_at: Date.now() }, |
| 230 | ]); |
| 231 | streamAnswer(resolvedThreadId, accepted.message_id); |
| 232 | setThreadsVersion((version) => version + 1); |
| 233 | } catch (err) { |
| 234 | setError(formatApiError(err)); |
| 235 | setDraft(content); |
| 236 | } finally { |
| 237 | setSending(false); |
| 238 | } |
| 239 | }; |
| 240 | |
| 241 | // The transcript follows the newest turn only while the reader is pinned to |
| 242 | // the bottom. Any upward scroll unpins at once — a distance threshold alone |
| 243 | // lost to a streamed answer that grows every frame and kept dragging the |
| 244 | // reader back down. Content that lands while unpinned raises the pill below |
| 245 | // instead of yanking the view. |
| 246 | let scroller: HTMLDivElement | undefined; |
| 247 | const NEAR_BOTTOM_PX = 64; |
| 248 | const [pinned, setPinned] = createSignal(true); |
| 249 | const [unread, setUnread] = createSignal(false); |
| 250 | let lastScrollTop = 0; |
| 251 | const scrollToLatest = () => { |
| 252 | if (!scroller) return; |
| 253 | setPinned(true); |
| 254 | setUnread(false); |
| 255 | scroller.scrollTo({ top: scroller.scrollHeight, behavior: "smooth" }); |
| 256 | }; |
| 257 | const handleTranscriptScroll = () => { |
| 258 | if (!scroller) return; |
| 259 | const top = scroller.scrollTop; |
| 260 | const distance = scroller.scrollHeight - top - scroller.clientHeight; |
| 261 | if (top < lastScrollTop - 1 && distance > 1) setPinned(false); |
| 262 | else if (distance <= NEAR_BOTTOM_PX) { |
| 263 | setPinned(true); |
| 264 | setUnread(false); |
| 265 | } |
| 266 | lastScrollTop = top; |
| 267 | }; |
| 268 | createEffect( |
| 269 | on( |
| 270 | () => { |
| 271 | const items = messages(); |
| 272 | return `${items.length}:${items[items.length - 1]?.content.length ?? 0}`; |
| 273 | }, |
| 274 | () => { |
| 275 | const el = scroller; |
| 276 | if (!el) return; |
| 277 | if (!pinned()) { setUnread(true); return; } |
| 278 | queueMicrotask(() => { |
| 279 | el.scrollTop = el.scrollHeight; |
| 280 | lastScrollTop = el.scrollTop; |
| 281 | }); |
| 282 | }, |
| 283 | { defer: true }, |
| 284 | ), |
| 285 | ); |
| 286 | |
| 287 | /** Re-ask the question an answer replies to, through the same send pipeline. */ |
| 288 | const retry = (question: string) => { |
| 289 | if (sending()) return; |
| 290 | setDraft(question); |
| 291 | void send(); |
| 292 | }; |
| 293 | |
| 294 | /** The user turn an answer replies to, used as the study range's label. */ |
| 295 | const questionBefore = (index: number) => { |
| 296 | for (let i = index - 1; i >= 0; i -= 1) if (messages()[i]?.role === "user") return messages()[i]!.content; |
| 297 | return undefined; |
| 298 | }; |
| 299 | |
| 300 | return ( |
| 301 | // Phones: one screen-tall column — top bar, transcript, composer — so the |
| 302 | // composer sits above the tab bar instead of scrolling away with the page. |
| 303 | // From lg the page fills the content column edge to edge, below the shell |
| 304 | // header: a flush history sidebar and the conversation beside it. |
| 305 | <div |
| 306 | class={cn( |
| 307 | "grid h-[calc(var(--app-viewport)-5.5rem-max(env(safe-area-inset-bottom),var(--android-nav-inset,0px)))] gap-4 max-lg:-mt-2", |
| 308 | "lg:-mx-10 lg:-my-6 lg:h-[calc(100dvh-49px-env(safe-area-inset-top))] lg:gap-0", |
| 309 | // The history docks on the RIGHT on desktop: on the left it sat flush |
| 310 | // against the app's own sidebar and the two read as one tangled nav. |
| 311 | historyCollapsed() ? "lg:grid-cols-[minmax(0,1fr)]" : "lg:grid-cols-[minmax(0,1fr)_260px]", |
| 312 | )} |
| 313 | > |
| 314 | <button |
| 315 | type="button" |
| 316 | tabIndex={-1} |
| 317 | aria-hidden="true" |
| 318 | class={cn( |
| 319 | "fixed inset-0 z-[55] bg-black/45 transition-opacity duration-300 lg:hidden", |
| 320 | historyOpen() ? "opacity-100" : "pointer-events-none opacity-0", |
| 321 | )} |
| 322 | onClick={() => setHistoryOpen(false)} |
| 323 | /> |
| 324 | <aside |
| 325 | aria-label={copy().history} |
| 326 | class={cn( |
| 327 | "flex min-h-0 flex-col gap-3 bg-surface-base", |
| 328 | // Phone drawer. `visibility` rides the transition so the panel |
| 329 | // slides out before it leaves the tab order. |
| 330 | "fixed inset-y-0 left-0 z-[60] w-[min(20rem,85vw)] border-r border-border-line px-3 pb-[calc(max(env(safe-area-inset-bottom),var(--android-nav-inset,0px))+0.75rem)] pt-[calc(env(safe-area-inset-top)+0.75rem)] shadow-xl transition-[transform,visibility] duration-300 ease-out", |
| 331 | historyOpen() ? "visible translate-x-0" : "invisible -translate-x-full", |
| 332 | "lg:visible lg:static lg:z-auto lg:h-full lg:w-auto lg:translate-x-0 lg:order-last lg:gap-2 lg:border-l lg:border-r-0 lg:border-border-hairline lg:bg-surface-overlay/40 lg:px-2 lg:py-3 lg:shadow-none lg:transition-none", |
| 333 | historyCollapsed() && "lg:hidden", |
| 334 | )} |
| 335 | > |
| 336 | {/* Vibe's sidebar head: the page's name, then its fold-away control. */} |
| 337 | <div class="flex h-10 items-center gap-1 pl-2.5 lg:h-9"> |
| 338 | <h2 class="min-w-0 flex-1 truncate text-sm font-semibold text-text-strong">{copy().title}</h2> |
| 339 | <button |
| 340 | type="button" |
| 341 | class="hidden h-8 w-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground outline-hidden transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring lg:inline-flex" |
| 342 | aria-label={copy().collapseHistory} |
| 343 | title={copy().collapseHistory} |
| 344 | onClick={() => setHistoryCollapsed(true)} |
| 345 | > |
| 346 | <IconPanelLeft class="h-4 w-4 -scale-x-100" /> |
| 347 | </button> |
| 348 | <button |
| 349 | type="button" |
| 350 | class="inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-lg text-muted-foreground outline-hidden transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring lg:hidden" |
| 351 | aria-label={copy().closeHistory} |
| 352 | onClick={() => setHistoryOpen(false)} |
| 353 | > |
| 354 | <IconX class="h-5 w-5" /> |
| 355 | </button> |
| 356 | </div> |
| 357 | {/* "New chat" is a nav row, filled while the new-chat screen is open. */} |
| 358 | <button |
| 359 | type="button" |
| 360 | class={cn( |
| 361 | "flex h-10 w-full items-center gap-2.5 rounded-lg px-2.5 text-sm text-foreground outline-hidden transition-colors focus-visible:ring-2 focus-visible:ring-ring lg:h-9", |
| 362 | threadId() ? "hover:bg-muted/60" : "bg-muted font-medium", |
| 363 | )} |
| 364 | onClick={() => { |
| 365 | setHistoryOpen(false); |
| 366 | newThread(); |
| 367 | }} |
| 368 | > |
| 369 | <IconPlus class="h-4 w-4 shrink-0" /> |
| 370 | <span class="truncate">{copy().newThread}</span> |
| 371 | </button> |
| 372 | {/* No "Recents" heading over an empty list: the empty state says it. */} |
| 373 | <Show when={knownThreads().length > 0}> |
| 374 | <h3 class="px-2.5 pb-0.5 pt-4 text-xs font-medium text-muted-foreground">{copy().recents}</h3> |
| 375 | </Show> |
| 376 | <RagThreadList |
| 377 | activeId={threadId()} |
| 378 | version={threadsVersion()} |
| 379 | locale={locale()} |
| 380 | labels={copy()} |
| 381 | onThreads={setKnownThreads} |
| 382 | onOpen={(thread) => { |
| 383 | setHistoryOpen(false); |
| 384 | openThread(thread); |
| 385 | }} |
| 386 | onRename={setRenaming} |
| 387 | onRemove={setRemoving} |
| 388 | /> |
| 389 | </aside> |
| 390 | |
| 391 | {/* No card, no header strip: the transcript sits on the page the way a |
| 392 | chat does. The conversation's own actions live on its row in the |
| 393 | sidebar, which is where they were already duplicated. */} |
| 394 | <section class="flex h-full min-h-0 flex-col" aria-label={copy().title}> |
| 395 | {/* Phone top bar: the drawer on the left, the open chat's name in the |
| 396 | middle, a fresh chat on the right. */} |
| 397 | <div class="flex shrink-0 items-center gap-2 border-b border-border-hairline pb-2 lg:hidden"> |
| 398 | <button |
| 399 | type="button" |
| 400 | class="inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-lg text-foreground outline-hidden transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring" |
| 401 | aria-label={copy().openHistory} |
| 402 | aria-expanded={historyOpen()} |
| 403 | onClick={() => setHistoryOpen(true)} |
| 404 | > |
| 405 | <IconMenu class="h-5 w-5" /> |
| 406 | </button> |
| 407 | <h1 class="min-w-0 flex-1 truncate text-center text-sm font-semibold text-text-strong"> |
| 408 | {activeThread()?.title || (threadId() ? copy().untitled : copy().title)} |
| 409 | </h1> |
| 410 | <button |
| 411 | type="button" |
| 412 | class="inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-lg text-foreground outline-hidden transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40" |
| 413 | aria-label={copy().newThread} |
| 414 | disabled={!threadId() && messages().length === 0} |
| 415 | onClick={newThread} |
| 416 | > |
| 417 | <IconPlus class="h-5 w-5" /> |
| 418 | </button> |
| 419 | </div> |
| 420 | {/* Desktop top bar: the open chat's title and its menu; with the |
| 421 | sidebar folded away, the way back to it and a fresh chat. */} |
| 422 | <div class="hidden h-12 shrink-0 items-center gap-1 px-3 lg:flex"> |
| 423 | <Show when={activeThread()}> |
| 424 | {(thread) => ( |
| 425 | <div class="flex min-w-0 items-center gap-1 pl-1"> |
| 426 | <DropdownMenu placement="bottom-start" gutter={6}> |
| 427 | <DropdownMenuTrigger class="flex min-w-0 items-center gap-1.5 rounded-lg px-2 py-1.5 text-sm font-medium text-text-strong outline-hidden transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring data-expanded:bg-muted"> |
| 428 | <span class="truncate">{thread().title || copy().untitled}</span> |
| 429 | <IconChevronDown class="h-3.5 w-3.5 shrink-0 opacity-60" /> |
| 430 | </DropdownMenuTrigger> |
| 431 | <DropdownMenuContent class="w-48"> |
| 432 | <DropdownMenuItem class="gap-2.5" onSelect={() => setRenaming(thread())}> |
| 433 | <IconEdit class="h-4 w-4" /> |
| 434 | {copy().rename} |
| 435 | </DropdownMenuItem> |
| 436 | <DropdownMenuSeparator /> |
| 437 | <DropdownMenuItem destructive class="gap-2.5" onSelect={() => setRemoving(thread())}> |
| 438 | <IconTrash class="h-4 w-4" /> |
| 439 | {copy().delete} |
| 440 | </DropdownMenuItem> |
| 441 | </DropdownMenuContent> |
| 442 | </DropdownMenu> |
| 443 | </div> |
| 444 | )} |
| 445 | </Show> |
| 446 | <Show when={historyCollapsed()}> |
| 447 | <div class="ml-auto flex items-center gap-1"> |
| 448 | <button |
| 449 | type="button" |
| 450 | class="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-muted-foreground outline-hidden transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring" |
| 451 | aria-label={copy().expandHistory} |
| 452 | title={copy().expandHistory} |
| 453 | onClick={() => setHistoryCollapsed(false)} |
| 454 | > |
| 455 | <IconPanelLeft class="h-4 w-4 -scale-x-100" /> |
| 456 | </button> |
| 457 | <button |
| 458 | type="button" |
| 459 | class="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-muted-foreground outline-hidden transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring" |
| 460 | aria-label={copy().newThread} |
| 461 | title={copy().newThread} |
| 462 | onClick={newThread} |
| 463 | > |
| 464 | <IconPlus class="h-4 w-4" /> |
| 465 | </button> |
| 466 | </div> |
| 467 | </Show> |
| 468 | </div> |
| 469 | <Show when={error()}> |
| 470 | <div class="mx-auto w-full max-w-3xl px-4 pt-1 sm:px-6"> |
| 471 | <Alert variant="destructive">{error()}</Alert> |
| 472 | </div> |
| 473 | </Show> |
| 474 | <div class="relative min-h-0 flex-1"> |
| 475 | <div ref={scroller} onScroll={handleTranscriptScroll} class="h-full overflow-y-auto px-4 py-5 sm:px-6" aria-live="polite"> |
| 476 | <div class="mx-auto w-full max-w-3xl space-y-6"> |
| 477 | <Show |
| 478 | when={messages().length > 0} |
| 479 | fallback={ |
| 480 | <Show |
| 481 | when={!loadingThread()} |
| 482 | fallback={ |
| 483 | <p class="flex min-h-[60vh] items-center justify-center text-sm text-muted-foreground lg:min-h-[calc(100dvh-16rem)]" role="status"> |
| 484 | {copy().loadingMessages} |
| 485 | </p> |
| 486 | } |
| 487 | > |
| 488 | {/* The landing screen centres the mark and the composer instead of |
| 489 | stranding the composer at the bottom of an empty page. */} |
| 490 | <div class="flex min-h-[60vh] flex-col justify-center lg:min-h-[calc(100dvh-16rem)]"> |
| 491 | <RagStudyWelcome title={greeting()} /> |
| 492 | <RagComposer |
| 493 | value={draft()} |
| 494 | placeholder={copy().placeholder} |
| 495 | sendLabel={copy().send} |
| 496 | hint={copy().emptyChatHint} |
| 497 | disabled={sending()} |
| 498 | autofocus |
| 499 | class="px-0 sm:px-0" |
| 500 | onInput={setDraft} |
| 501 | onSubmit={() => void send()} |
| 502 | /> |
| 503 | </div> |
| 504 | </Show> |
| 505 | } |
| 506 | > |
| 507 | <For each={messages()}> |
| 508 | {(message, index) => { |
| 509 | const scope = () => |
| 510 | message.role === "assistant" && message.status === "complete" && !message.abstained |
| 511 | ? scopeFromCitations(message.citations, questionBefore(index())) |
| 512 | : null; |
| 513 | const question = () => questionBefore(index()); |
| 514 | const retryable = () => |
| 515 | message.role === "assistant" && |
| 516 | index() === messages().length - 1 && |
| 517 | (message.status === "complete" || message.status === "failed") && |
| 518 | question() != null; |
| 519 | return ( |
| 520 | <RagMessageRow |
| 521 | message={message} |
| 522 | labels={copy()} |
| 523 | onRetry={retryable() ? () => retry(question()!) : undefined} |
| 524 | footer={ |
| 525 | <Show when={scope()}> |
| 526 | {(current) => ( |
| 527 | <RagStudyActions |
| 528 | scope={current()} |
| 529 | copy={copy()} |
| 530 | unavailable={studyUnavailable()} |
| 531 | onUnavailable={() => setStudyUnavailable(true)} |
| 532 | /> |
| 533 | )} |
| 534 | </Show> |
| 535 | } |
| 536 | /> |
| 537 | ); |
| 538 | }} |
| 539 | </For> |
| 540 | </Show> |
| 541 | </div> |
| 542 | </div> |
| 543 | <Show when={!pinned()}> |
| 544 | <button |
| 545 | type="button" |
| 546 | class={cn( |
| 547 | "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", |
| 548 | unread() |
| 549 | ? "border-transparent bg-primary bg-clip-padding text-primary-foreground hover:bg-primary/90" |
| 550 | : "border-border bg-surface-base/95 text-foreground hover:bg-surface-overlay", |
| 551 | )} |
| 552 | onClick={scrollToLatest} |
| 553 | > |
| 554 | <IconChevronDown class="h-3.5 w-3.5" /> |
| 555 | {unread() ? copy().newMessages : copy().scrollToLatest} |
| 556 | </button> |
| 557 | </Show> |
| 558 | </div> |
| 559 | <Show when={messages().length > 0}> |
| 560 | <RagComposer |
| 561 | value={draft()} |
| 562 | placeholder={copy().placeholder} |
| 563 | sendLabel={copy().send} |
| 564 | hint={copy().emptyChatHint} |
| 565 | disabled={sending()} |
| 566 | autofocus |
| 567 | class="pb-4" |
| 568 | onInput={setDraft} |
| 569 | onSubmit={() => void send()} |
| 570 | /> |
| 571 | </Show> |
| 572 | </section> |
| 573 | |
| 574 | <ConfirmDialog |
| 575 | open={renaming() != null} |
| 576 | onOpenChange={(open) => !open && setRenaming(null)} |
| 577 | title={copy().rename} |
| 578 | description={copy().renameHint} |
| 579 | summary={renaming()?.title || copy().untitled} |
| 580 | confirmLabel={copy().rename} |
| 581 | prompt={{ label: copy().renameLabel, placeholder: copy().renamePlaceholder, maxLength: 200, initialValue: renaming()?.title ?? "", singleLine: true }} |
| 582 | onConfirm={async (title) => { |
| 583 | const thread = renaming(); |
| 584 | if (!thread) return; |
| 585 | const nextTitle = title?.trim() || null; |
| 586 | await patchRagThreadById(thread.id, nextTitle); |
| 587 | if (activeThread()?.id === thread.id) setActiveThread({ ...activeThread()!, title: nextTitle }); |
| 588 | setThreadsVersion((version) => version + 1); |
| 589 | }} |
| 590 | /> |
| 591 | <ConfirmDialog |
| 592 | open={removing() != null} |
| 593 | onOpenChange={(open) => !open && setRemoving(null)} |
| 594 | title={copy().delete} |
| 595 | description={copy().deleteHint} |
| 596 | summary={removing()?.title || copy().untitled} |
| 597 | confirmLabel={copy().deleteConfirm} |
| 598 | variant="destructive" |
| 599 | onConfirm={async () => { |
| 600 | const thread = removing(); |
| 601 | if (!thread) return; |
| 602 | await deleteRagThreadById(thread.id); |
| 603 | if (threadId() === thread.id) newThread(); |
| 604 | setThreadsVersion((version) => version + 1); |
| 605 | }} |
| 606 | /> |
| 607 | </div> |
| 608 | ); |
| 609 | } |