backend / frontend /src /pages /ChatPage.jsx
muhammadhasnain100's picture
Cursor
Add FastAPI routes, admin panel, RAG CSV merge, React frontend
c5cf697
Raw History Blame Contribute Delete
15.4 kB
import { useCallback, useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import {
createChat,
fetchChatPage,
listChats,
removeChat,
sendMessage,
} from '../api/chat'
import { clearSession, getStoredUser } from '../auth/storage'
import ChatMain from '../components/chat/ChatMain'
import CollapsedSidebarRail from '../components/chat/CollapsedSidebarRail'
import ChatSidebar from '../components/chat/ChatSidebar'
import ProfileModal from '../components/chat/ProfileModal'
const THREAD_LIMIT = 20
const SIDEBAR_LIMIT = 25
const SUGGESTIONS_PREF_KEY = 'comsats_suggestions_enabled'
const WEB_SEARCH_PREF_KEY = 'comsats_use_web_search'
function readSuggestionsPref() {
try {
return localStorage.getItem(SUGGESTIONS_PREF_KEY) !== 'false'
} catch {
return true
}
}
function readWebSearchPref() {
try {
const raw = localStorage.getItem(WEB_SEARCH_PREF_KEY)
if (raw === null) {
localStorage.setItem(WEB_SEARCH_PREF_KEY, 'false')
return false
}
return raw === 'true'
} catch {
return false
}
}
function enrichSlice(slice, rangeStart) {
return slice.map((pair, i) => ({
question: pair.question,
answer: pair.answer,
pairIndex: rangeStart + i,
pending: false,
}))
}
export default function ChatPage() {
const navigate = useNavigate()
const user = getStoredUser()
const scrollRef = useRef(null)
const [chats, setChats] = useState([])
const [chatListTotal, setChatListTotal] = useState(0)
const [chatListHasMore, setChatListHasMore] = useState(false)
const [loadingMoreChats, setLoadingMoreChats] = useState(false)
const [selectedId, setSelectedId] = useState(null)
const [turns, setTurns] = useState([])
const [nextBeforeIndex, setNextBeforeIndex] = useState(null)
const [hasOlder, setHasOlder] = useState(false)
const [totalPairs, setTotalPairs] = useState(0)
const [question, setQuestion] = useState('')
const [loadingList, setLoadingList] = useState(true)
const [loadingChat, setLoadingChat] = useState(false)
const [loadingOlder, setLoadingOlder] = useState(false)
const [sending, setSending] = useState(false)
const [sendError, setSendError] = useState('')
const [profileOpen, setProfileOpen] = useState(false)
const [tailBump, setTailBump] = useState(0)
const [followUpSuggestions, setFollowUpSuggestions] = useState([])
const [suggestionsEnabled, setSuggestionsEnabled] = useState(readSuggestionsPref)
const [webSearchEnabled, setWebSearchEnabled] = useState(() =>
readWebSearchPref(),
)
const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false)
const [desktopSidebarOpen, setDesktopSidebarOpen] = useState(true)
const [viewportMd, setViewportMd] = useState(() =>
typeof window !== 'undefined' ? window.matchMedia('(min-width: 768px)').matches : true,
)
const emptyListBootstrapRef = useRef(false)
const chatsRef = useRef([])
chatsRef.current = chats
const loadSidebarFirstPage = useCallback(async () => {
setLoadingList(true)
try {
const data = await listChats({ skip: 0, limit: SIDEBAR_LIMIT })
setChats(data.chats || [])
setChatListTotal(data.total ?? 0)
setChatListHasMore(!!data.has_more)
} catch {
setChats([])
setChatListTotal(0)
setChatListHasMore(false)
} finally {
setLoadingList(false)
}
}, [])
const loadMoreSidebarChats = useCallback(async () => {
setLoadingMoreChats(true)
try {
const data = await listChats({
skip: chatsRef.current.length,
limit: SIDEBAR_LIMIT,
})
const batch = data.chats || []
setChats((prev) => {
const seen = new Set(prev.map((c) => c.chat_id))
const merged = [...prev]
for (const c of batch) {
if (!seen.has(c.chat_id)) merged.push(c)
}
return merged
})
setChatListTotal(data.total ?? 0)
setChatListHasMore(!!data.has_more)
} catch {
/* keep existing */
} finally {
setLoadingMoreChats(false)
}
}, [])
useEffect(() => {
loadSidebarFirstPage()
}, [loadSidebarFirstPage])
useEffect(() => {
const mq = window.matchMedia('(min-width: 768px)')
function onViewportChange() {
const md = mq.matches
setViewportMd(md)
if (md) setMobileSidebarOpen(false)
}
onViewportChange()
mq.addEventListener('change', onViewportChange)
return () => mq.removeEventListener('change', onViewportChange)
}, [])
useEffect(() => {
try {
localStorage.setItem(SUGGESTIONS_PREF_KEY, String(suggestionsEnabled))
} catch {
/* ignore */
}
if (!suggestionsEnabled) setFollowUpSuggestions([])
}, [suggestionsEnabled])
useEffect(() => {
try {
localStorage.setItem(WEB_SEARCH_PREF_KEY, String(webSearchEnabled))
} catch {
/* ignore */
}
}, [webSearchEnabled])
const selectChat = useCallback(async (chatId) => {
setSelectedId(chatId)
setLoadingChat(true)
setSendError('')
setFollowUpSuggestions([])
setTurns([])
setHasOlder(false)
setNextBeforeIndex(null)
setTotalPairs(0)
try {
const data = await fetchChatPage(chatId, { limit: THREAD_LIMIT })
const slice = data.history || []
const rangeStart = data.range_start ?? 0
setTurns(enrichSlice(slice, rangeStart))
setTotalPairs(data.total_pairs ?? slice.length)
setHasOlder(!!data.has_older)
setNextBeforeIndex(
data.next_before_index != null ? data.next_before_index : rangeStart,
)
} catch {
setTurns([])
setSendError('Could not load this chat.')
} finally {
setLoadingChat(false)
}
}, [])
useEffect(() => {
if (loadingList) return
if (chats.length === 0) {
if (emptyListBootstrapRef.current) return
emptyListBootstrapRef.current = true
;(async () => {
try {
const created = await createChat()
const id = created.chat_id
setChats([
{
chat_id: id,
preview: 'New conversation',
updated_at: null,
message_count: 0,
},
])
setChatListTotal(1)
setChatListHasMore(false)
setSelectedId(id)
setFollowUpSuggestions([])
setTurns([])
setHasOlder(false)
setNextBeforeIndex(null)
setTotalPairs(0)
} catch {
setSendError('Could not start a chat. Is the API running on port 8000?')
}
})()
return
}
if (!selectedId && chats[0]) {
selectChat(chats[0].chat_id)
}
}, [loadingList, chats, selectedId, selectChat])
async function handleLoadOlderMessages() {
if (!selectedId || !hasOlder || loadingOlder) return
const beforeIdx =
nextBeforeIndex != null ? nextBeforeIndex : turns[0]?.pairIndex ?? 0
const el = scrollRef.current
const prevScrollHeight = el?.scrollHeight ?? 0
const prevScrollTop = el?.scrollTop ?? 0
setLoadingOlder(true)
try {
const data = await fetchChatPage(selectedId, {
beforeIndex: beforeIdx,
limit: THREAD_LIMIT,
})
const slice = data.history || []
const rangeStart = data.range_start ?? 0
const older = enrichSlice(slice, rangeStart)
setTurns((prev) => [...older, ...prev])
setHasOlder(!!data.has_older)
setNextBeforeIndex(data.next_before_index ?? 0)
requestAnimationFrame(() => {
const el2 = scrollRef.current
if (el2) {
el2.scrollTop = el2.scrollHeight - prevScrollHeight + prevScrollTop
}
})
} catch (e) {
setSendError(e.message || 'Could not load older messages')
} finally {
setLoadingOlder(false)
}
}
async function handleNewChat() {
setSendError('')
try {
const created = await createChat()
const id = created.chat_id
const entry = {
chat_id: id,
preview: 'New conversation',
updated_at: null,
message_count: 0,
}
setChats((prev) => [entry, ...prev.filter((c) => c.chat_id !== id)])
setChatListTotal((t) => t + 1)
setSelectedId(id)
setFollowUpSuggestions([])
setTurns([])
setHasOlder(false)
setNextBeforeIndex(null)
setTotalPairs(0)
setTailBump((x) => x + 1)
} catch (e) {
setSendError(e.message || 'Could not create chat')
}
}
async function handleDeleteChat(chatId) {
if (!window.confirm('Delete this conversation?')) return
try {
await removeChat(chatId)
const remaining = chats.filter((c) => c.chat_id !== chatId)
setChats(remaining)
setChatListTotal((t) => Math.max(0, t - 1))
if (selectedId === chatId) {
if (remaining.length > 0) {
await selectChat(remaining[0].chat_id)
} else {
emptyListBootstrapRef.current = false
const created = await createChat()
const id = created.chat_id
setChats([
{
chat_id: id,
preview: 'New conversation',
updated_at: null,
message_count: 0,
},
])
setChatListTotal(1)
setChatListHasMore(false)
setSelectedId(id)
setFollowUpSuggestions([])
setTurns([])
setHasOlder(false)
setNextBeforeIndex(null)
setTotalPairs(0)
emptyListBootstrapRef.current = true
}
}
} catch (e) {
setSendError(e.message || 'Could not delete chat')
}
}
async function handleSend(overrideText) {
const raw =
overrideText !== undefined && overrideText !== null
? String(overrideText)
: question
const q = raw.trim()
if (!selectedId || !q || sending) return
const clientKey = crypto.randomUUID()
const pairIdx = totalPairs
setSendError('')
setSending(true)
setQuestion('')
setTurns((prev) => [
...prev,
{
question: q,
answer: null,
pending: true,
clientKey,
},
])
setTailBump((x) => x + 1)
try {
const res = await sendMessage(selectedId, q, {
allowAugmentation: suggestionsEnabled,
useWebSearch: webSearchEnabled,
})
const answer = res.answer
if (suggestionsEnabled) {
setFollowUpSuggestions(
Array.isArray(res.suggested_questions) ? res.suggested_questions : [],
)
} else {
setFollowUpSuggestions([])
}
setTurns((prev) =>
prev.map((t) =>
t.clientKey === clientKey
? {
question: q,
answer,
pending: false,
pairIndex: pairIdx,
}
: t,
),
)
setTotalPairs((n) => n + 1)
setTailBump((x) => x + 1)
setChats((prev) =>
prev.map((c) =>
c.chat_id === selectedId
? {
...c,
preview: q.slice(0, 100),
message_count: (c.message_count || 0) + 1,
}
: c,
),
)
} catch (e) {
setFollowUpSuggestions([])
setTurns((prev) => prev.filter((t) => t.clientKey !== clientKey))
setQuestion(q)
setSendError(e.message || 'Failed to send')
} finally {
setSending(false)
}
}
function logout() {
clearSession()
navigate('/login', { replace: true })
}
const selectedChat = selectedId
? chats.find((c) => c.chat_id === selectedId)
: null
const chatTitle = selectedChat?.preview?.trim() || 'New conversation'
function closeMobileSidebar() {
setMobileSidebarOpen(false)
}
function handleCloseSidebar() {
if (viewportMd) setDesktopSidebarOpen(false)
else closeMobileSidebar()
}
function handleOpenSidebar() {
if (viewportMd) setDesktopSidebarOpen(true)
else setMobileSidebarOpen(true)
}
const sidebarExpanded = viewportMd ? desktopSidebarOpen : mobileSidebarOpen
const collapsedSidebarRail = viewportMd && !desktopSidebarOpen
return (
<div className="relative flex h-dvh min-h-0 w-full overflow-hidden bg-chat-canvas md:bg-white">
{mobileSidebarOpen ? (
<button
type="button"
aria-label="Close sidebar"
className="fixed inset-0 z-30 bg-slate-900/35 backdrop-blur-[1px] md:hidden"
onClick={closeMobileSidebar}
/>
) : null}
<div
className={`fixed inset-y-0 left-0 z-40 flex h-dvh shrink-0 flex-col overflow-hidden border-r border-slate-200/70 bg-chat-sidebar shadow-[4px_0_24px_rgba(0,0,0,0.08)] transition-[transform,width,min-width,max-width] duration-200 ease-out md:z-0 md:shadow-none ${
mobileSidebarOpen ? 'translate-x-0' : '-translate-x-full md:translate-x-0'
} ${
desktopSidebarOpen
? 'w-[min(92vw,360px)] md:relative md:w-[320px] md:min-w-[320px] lg:w-[360px] lg:min-w-[360px]'
: 'w-[min(92vw,360px)] md:relative md:w-0 md:min-w-0 md:max-w-0 md:border-r-0 md:opacity-0 md:pointer-events-none'
}`}
>
<ChatSidebar
user={user}
chats={chats}
selectedId={selectedId}
onCloseSidebar={handleCloseSidebar}
onSelectChat={(id) => {
selectChat(id)
closeMobileSidebar()
}}
onNewChat={() => {
handleNewChat()
closeMobileSidebar()
}}
onDeleteChat={handleDeleteChat}
onEditProfile={() => {
setProfileOpen(true)
closeMobileSidebar()
}}
onLogout={() => {
logout()
closeMobileSidebar()
}}
loadingList={loadingList}
hasMoreChats={chatListHasMore}
loadingMoreChats={loadingMoreChats}
onLoadMoreChats={loadMoreSidebarChats}
chatListTotal={chatListTotal}
/>
</div>
<div className="flex min-h-0 min-w-0 flex-1 md:bg-chat-canvas">
{collapsedSidebarRail ? (
<CollapsedSidebarRail
onOpenSidebar={handleOpenSidebar}
onEditProfile={() => setProfileOpen(true)}
onLogout={logout}
/>
) : null}
<div className="flex min-h-0 min-w-0 flex-1 flex-col">
<ChatMain
ref={scrollRef}
chatId={selectedId}
chatTitle={chatTitle}
turns={turns}
loadingChat={loadingChat}
loadingOlder={loadingOlder}
hasOlder={hasOlder}
onLoadOlder={handleLoadOlderMessages}
sending={sending}
tailBump={tailBump}
error={sendError}
question={question}
setQuestion={setQuestion}
onSend={handleSend}
followUpSuggestions={followUpSuggestions}
suggestionsEnabled={suggestionsEnabled}
onSuggestionsEnabledChange={setSuggestionsEnabled}
webSearchEnabled={webSearchEnabled}
onWebSearchEnabledChange={setWebSearchEnabled}
onPickFollowUp={(text) => handleSend(text)}
sidebarExpanded={sidebarExpanded}
collapsedSidebarRail={collapsedSidebarRail}
onOpenSidebar={handleOpenSidebar}
/>
</div>
</div>
<ProfileModal open={profileOpen} onClose={() => setProfileOpen(false)} />
</div>
)
}