"use client"; import { useEffect, useMemo, useRef, useState } from "react"; import { Check, History as HistoryIcon, Loader2, MessageSquare, Search, Sparkles, UserRound, } from "lucide-react"; import { useTranslation } from "react-i18next"; import PickerShell from "@/components/common/PickerShell"; import PickerHeader from "@/components/common/PickerHeader"; import { getSession, listSessions, searchSessions, type SessionDetail, type SessionSearchResult, type SessionSummary, } from "@/lib/session-api"; import { normalizeMessageContent, truncateText } from "@/lib/message-content"; import { displaySessionTitle } from "@/lib/session-title"; export interface SelectedHistorySession { sessionId: string; title: string; } interface HistorySessionPickerProps { open: boolean; onClose: () => void; onApply: (sessions: SelectedHistorySession[]) => void; } /** * Format a backend session timestamp (stored as float seconds via time.time()) * into a localized string. Returns an empty string when the timestamp is * missing or non-positive so we don't render nonsensical 1970 dates. */ function formatSessionTimestamp(value?: number): string { if (!value || value <= 0) return ""; // Backend stores REAL seconds. JS Date expects milliseconds. return new Date(value * 1000).toLocaleString(); } function sessionKey(session: SessionSummary): string { return session.session_id || session.id; } export default function HistorySessionPicker({ open, onClose, onApply, }: HistorySessionPickerProps) { const { t } = useTranslation(); // Backend writes the English sentinel "New conversation" until the LLM // title lands; mirror SessionList with a localized "New chat" label. const placeholderLabel = t("New chat"); const [sessions, setSessions] = useState([]); const [selectedSessions, setSelectedSessions] = useState< Record >({}); const [query, setQuery] = useState(""); const queryRef = useRef(query); const [loading, setLoading] = useState(false); const [searchResults, setSearchResults] = useState([]); const [searchTotal, setSearchTotal] = useState(0); const [searchLoading, setSearchLoading] = useState(false); const [loadingMore, setLoadingMore] = useState(false); const searchGenerationRef = useRef(0); const loadMoreAbortRef = useRef(null); const selectedIds = Object.keys(selectedSessions); // The session shown in the right-hand preview pane. Driven by hover/focus // and click so the preview tracks wherever the user's attention is — the // list reads like a mail client: glide over a row, see its conversation. const [activeId, setActiveId] = useState(null); // Fetched session transcripts, cached so re-hovering a row is instant. const [details, setDetails] = useState>({}); const detailsRef = useRef(details); useEffect(() => { detailsRef.current = details; }, [details]); const [previewLoadingId, setPreviewLoadingId] = useState(null); useEffect(() => { if (!open) return; let mounted = true; const load = async () => { setLoading(true); try { const data = await listSessions(200, 0, { force: true }); if (!mounted) return; setSessions(data); if (queryRef.current.trim()) return; // Default the preview to the most recent session so the right pane is // never blank on open. setActiveId((prev) => { if (prev && data.some((s) => sessionKey(s) === prev)) return prev; return data.length ? sessionKey(data[0]) : null; }); } catch { if (!mounted) return; setSessions([]); } finally { if (mounted) setLoading(false); } }; void load(); return () => { mounted = false; }; }, [open]); useEffect(() => { const generation = ++searchGenerationRef.current; loadMoreAbortRef.current?.abort(); loadMoreAbortRef.current = null; setLoadingMore(false); const term = query.trim(); if (!open || !term) { setSearchResults([]); setSearchTotal(0); setSearchLoading(false); return; } setSearchResults([]); setSearchTotal(0); setSearchLoading(true); let controller: AbortController | null = null; const timer = window.setTimeout(() => { controller = new AbortController(); searchSessions(term, 50, 0, controller.signal) .then((page) => { if (generation !== searchGenerationRef.current) return; setSearchResults(page.sessions); setSearchTotal(page.total); setActiveId(page.sessions[0] ? sessionKey(page.sessions[0]) : null); }) .catch((error: unknown) => { if (error instanceof DOMException && error.name === "AbortError") return; if (generation !== searchGenerationRef.current) return; setSearchResults([]); setSearchTotal(0); }) .finally(() => { if (generation === searchGenerationRef.current) setSearchLoading(false); }); }, 300); return () => { window.clearTimeout(timer); controller?.abort(); }; }, [open, query]); // Lazily fetch the active session's transcript for the preview pane. useEffect(() => { if (!open || !activeId) return; if (detailsRef.current[activeId]) return; let cancelled = false; setPreviewLoadingId(activeId); getSession(activeId) .then((detail) => { if (cancelled) return; setDetails((prev) => ({ ...prev, [activeId]: detail })); }) .catch(() => { /* preview is best-effort; the list still works without it */ }) .finally(() => { if (cancelled) return; setPreviewLoadingId((cur) => (cur === activeId ? null : cur)); }); return () => { cancelled = true; }; }, [activeId, open]); const searching = query.trim().length > 0; const visibleSessions: SessionSummary[] = searching ? searchResults : sessions; const toggleSession = (session: SessionSummary) => { const id = sessionKey(session); setSelectedSessions((prev) => { if (!prev[id]) return { ...prev, [id]: session }; const next = { ...prev }; delete next[id]; return next; }); }; const handleApply = () => { const selected = selectedIds .map((id) => selectedSessions[id]) .filter((session): session is SessionSummary => Boolean(session)) .map((session) => ({ sessionId: sessionKey(session), title: displaySessionTitle(session.title, placeholderLabel), })); onApply(selected); onClose(); }; const activeSession = activeId ? visibleSessions.find((s) => sessionKey(s) === activeId) : undefined; const activeSearchResult = searching && activeId ? searchResults.find((s) => sessionKey(s) === activeId) : undefined; const activeDetail = activeId ? details[activeId] : undefined; const activeLoading = previewLoadingId !== null && previewLoadingId === activeId; return (
{/* ── Left: searchable, selectable session list ── */}
{ queryRef.current = event.target.value; setQuery(event.target.value); }} maxLength={200} placeholder={t("Search full conversation history")} className="w-full rounded-xl border border-[var(--border)] bg-[var(--card)] py-2.5 pl-9 pr-3 text-[13px] text-[var(--foreground)] outline-none transition focus:border-[var(--primary)]/50 focus:ring-2 focus:ring-[var(--primary)]/15" />
{selectedIds.length > 0 && ( )}
{(searching ? searchLoading : loading) ? (
) : visibleSessions.length ? (
{visibleSessions.map((session) => { const id = sessionKey(session); const selected = selectedIds.includes(id); const active = id === activeId; const searchResult = searching ? (session as SessionSearchResult) : null; return ( ); })} {searching && searchResults.length < searchTotal && ( )}
) : (
{t("No matching sessions found.")}
)}
{/* ── Right: live preview of the focused session ── */}
{activeSession ? ( <>
{displaySessionTitle( activeSession.title, placeholderLabel, )}
{activeSession.message_count ?? 0} {t("messages")} {formatSessionTimestamp( activeSession.updated_at || activeSession.created_at, ) && ( {formatSessionTimestamp( activeSession.updated_at || activeSession.created_at, )} )}
{selectedIds.includes(activeId!) && ( {t("Selected")} )}
{activeLoading && !activeDetail ? (
{t("Loading preview…")}
) : activeDetail ? ( ) : (
{t("No messages in this session.")}
)}
) : (

{t("Select a session to preview it here.")}

)}
{selectedIds.length === 1 ? t("1 session selected") : t("{{n}} sessions selected", { n: selectedIds.length })}
); } /** * Read-only transcript rendering for the preview pane. We render the stored * final `content` of each message (not the streaming trace) as plain, * role-labelled text — enough to recognize a conversation at a glance without * pulling in the full markdown/KaTeX renderer. */ function ConversationPreview({ detail, focusMessageId, }: { detail: SessionDetail; focusMessageId?: number | string | null; }) { const { t } = useTranslation(); const messageRefs = useRef(new Map()); const turns = useMemo( () => (detail.messages || []) .filter((m) => m.role === "user" || m.role === "assistant") .map((m) => ({ id: m.id, role: m.role, text: truncateText(normalizeMessageContent(m.content), 1400), })) .filter((m) => m.text.trim().length > 0), [detail.messages], ); useEffect(() => { if (focusMessageId === null || focusMessageId === undefined) return; messageRefs.current .get(String(focusMessageId)) ?.scrollIntoView?.({ block: "center" }); }, [focusMessageId, turns]); if (turns.length === 0) { return (
{t("No messages in this session.")}
); } return (
{turns.map((turn) => { const isUser = turn.role === "user"; return (
{ const key = String(turn.id); if (node) messageRefs.current.set(key, node); else messageRefs.current.delete(key); }} className={ focusMessageId !== null && focusMessageId !== undefined && String(turn.id) === String(focusMessageId) ? "rounded-xl bg-[var(--primary)]/[0.06] p-3 ring-1 ring-[var(--primary)]/20" : undefined } >
{isUser ? ( ) : ( )} {isUser ? t("You") : t("Assistant")}
{turn.text}
); })}
); }