"use client"; import { pageGridClass } from '@/components/layout/FeaturePage' import { navigateTask } from "@/lib/workspace-scope"; import { sessionWorkspaceId } from "@/lib/session-api"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useRouter } from "next/navigation"; import { History, Loader2, RefreshCw, Search, type LucideIcon, } from "lucide-react"; import { useTranslation } from "react-i18next"; import OrganizedSessionList from "@/components/sessions/OrganizedSessionList"; import ArchivedConversations from "@/components/space/ArchivedConversations"; import SpaceSectionHeader from "@/components/space/SpaceSectionHeader"; import { useAppShell } from "@/context/AppShellContext"; import { fetchMasteryTopicIndex, type MasteryTopicLabel, } from "@/lib/learning-api"; import { sessionRoute } from "@/lib/mastery-session"; import { fetchReadingCollectionIndex, type ReadingCollectionLabel, } from "@/lib/reading-workspace-api"; import { collectArchivedConversations } from "@/lib/session-archive"; import { notifySessionsChanged } from "@/lib/session-events"; import { deleteSession, listAllSessions, searchAllSessions, updateSessionTitle, updateSessionOrganization, type SessionOrganizationPatch, type SessionSearchResult, type SessionSummary, } from "@/lib/session-api"; /** * The learning space's conversation history: search, filter, and the archive. * * A conversation reopens on the surface it was held in (see ``sessionRoute``), * not always in the main chat. This page used to send everything to `/chat`, * which for a reading conversation meant reopening it with its material closed * and its citations pointing at a document that is not on screen. */ export interface ChatHistorySectionProps { icon?: LucideIcon; title?: string; description?: string; } export default function ChatHistorySection({ icon, title, description, }: ChatHistorySectionProps = {}) { const basePath = "/chat"; const { t } = useTranslation(); const router = useRouter(); const { activeSessionId, setActiveSessionId } = useAppShell(); const [sessions, setSessions] = useState([]); const [masteryTopics, setMasteryTopics] = useState([]); const [readingCollections, setReadingCollections] = useState< ReadingCollectionLabel[] >([]); const [loading, setLoading] = useState(true); const [restoringId, setRestoringId] = useState(null); const [query, setQuery] = useState(""); const [searchResults, setSearchResults] = useState([]); const [searchLoading, setSearchLoading] = useState(false); const [searchError, setSearchError] = useState(false); const [searchVersion, setSearchVersion] = useState(0); const searchGenerationRef = useRef(0); const [kindFilter, setKindFilter] = useState("all"); const [archiveFilter, setArchiveFilter] = useState("active"); // ``quiet`` refetches without swapping the panel for its skeleton: a restore // acts on one row and says so on that row, so blanking the whole archive // underneath it would be the only thing the eye followed. const load = useCallback(async (force = false, quiet = false) => { if (!quiet) setLoading(true); try { // Topic and collection labels only name which surface an archived // conversation came from, so losing them costs that line, never the // conversation. const [nextSessions, nextTopics, nextCollections] = await Promise.all([ listAllSessions({ force }), fetchMasteryTopicIndex().catch(() => [] as MasteryTopicLabel[]), fetchReadingCollectionIndex().catch( () => [] as ReadingCollectionLabel[], ), ]); setSessions(nextSessions); setMasteryTopics(nextTopics); setReadingCollections(nextCollections); } finally { if (!quiet) setLoading(false); } }, []); const reload = useCallback( async (force = false, quiet = false) => { await load(force, quiet); setSearchVersion((version) => version + 1); }, [load], ); useEffect(() => { void load(true); }, [load]); useEffect(() => { const generation = ++searchGenerationRef.current; const term = query.trim(); setSearchError(false); if (!term) { setSearchResults([]); setSearchLoading(false); return; } setSearchResults([]); setSearchLoading(true); let controller: AbortController | null = null; const timer = window.setTimeout(() => { controller = new AbortController(); searchAllSessions(term, controller.signal) .then((results) => { if (generation !== searchGenerationRef.current) return; setSearchResults(results); }) .catch((error: unknown) => { if (error instanceof DOMException && error.name === "AbortError") return; if (generation !== searchGenerationRef.current) return; setSearchResults([]); setSearchError(true); }) .finally(() => { if (generation === searchGenerationRef.current) setSearchLoading(false); }); }, 300); return () => { window.clearTimeout(timer); controller?.abort(); }; }, [query, searchVersion]); const filteredSessions = useMemo(() => { const source = query.trim() ? searchResults : sessions; return source.filter((session) => { const prefs = session.preferences ?? {}; if (archiveFilter === "active" && prefs.archived) return false; if (archiveFilter === "archived" && !prefs.archived) return false; if (kindFilter === "chat" && prefs.session_kind === "selection_tutor") return false; if ( kindFilter === "selection_tutor" && prefs.session_kind !== "selection_tutor" ) return false; return true; }); }, [archiveFilter, kindFilter, query, searchResults, sessions]); const handleSelect = useCallback( (sessionId: string) => { setActiveSessionId(sessionId); const session = filteredSessions.find( (item) => item.session_id === sessionId, ); navigateTask(session ? sessionRoute(session) : `${basePath}/${sessionId}`, router.push); }, [basePath, filteredSessions, router, setActiveSessionId], ); const handleRename = useCallback( async (sessionId: string, title: string) => { await updateSessionTitle( sessionId, title, sessionWorkspaceId( filteredSessions.find((item) => item.session_id === sessionId), ), ); await reload(true); }, [filteredSessions, reload], ); const handleDelete = useCallback( async (sessionId: string) => { if (!window.confirm(t("Permanently delete this chat and its tutor threads? This cannot be undone."))) return; await deleteSession( sessionId, sessionWorkspaceId( filteredSessions.find((item) => item.session_id === sessionId), ), ); if (activeSessionId === sessionId) setActiveSessionId(null); setSessions((prev) => prev.filter((session) => session.session_id !== sessionId), ); setSearchResults((prev) => prev.filter((session) => session.session_id !== sessionId), ); setSearchVersion((version) => version + 1); }, [activeSessionId, filteredSessions, setActiveSessionId, t], ); // The archived view is built from the same filtered set as the list, so the // search box and the type filter still narrow it. const archiveBuckets = useMemo( () => collectArchivedConversations({ sessions: filteredSessions, masteryTopics, readingCollections, }), [filteredSessions, masteryTopics, readingCollections], ); const handleRestore = useCallback( async (sessionId: string) => { setRestoringId(sessionId); try { await updateSessionOrganization( sessionId, { archived: false }, sessionWorkspaceId( filteredSessions.find((item) => item.session_id === sessionId), ), ); // Restoring cascades to the tutor threads under the conversation, so // the server's own list is what says which rows are left. await reload(true, true); notifySessionsChanged(); } finally { setRestoringId(null); } }, [filteredSessions, reload], ); const handleOrganize = useCallback( async (sessionId: string, patch: SessionOrganizationPatch) => { await updateSessionOrganization( sessionId, patch, sessionWorkspaceId( filteredSessions.find((item) => item.session_id === sessionId), ), ); await reload(true); // Archiving or restoring here changes what the sidebar beside this page // is allowed to show, and that list was fetched when the shell mounted. notifySessionsChanged(); }, [filteredSessions, reload], ); const HeaderIcon = icon ?? History; const headerTitle = title ?? t("Chat History"); const headerDescription = description ?? t( "Browse, rename, delete, and reopen previous conversations from your learning space.", ); return (
{sessions.length} {t("conversations")} } action={ } />
{loading || searchLoading ? (
{[0, 1, 2, 3].map((item) => (
))}
) : searchError ? (

{t("Could not search chat history. Try again.")}

) : archiveFilter === "archived" ? ( ) : ( )}
); }