"use client"; import React, { useState, useEffect, useRef } from "react"; import type { AnswerBlock, ChatMessage, Citation, DrugSectionOption, MonographPickerState, SendMessageResponse, } from "@duoc-thu/shared-types"; import { ChatBubble, CitationBeamOverlay, useTheme } from "@duoc-thu/ui"; import { Composer } from "./Composer"; import { AnswerFeedback } from "./AnswerFeedback"; import { Sparkles, Pill, ShieldCheck, BookOpen, Activity, Zap, Info, AlertCircle, Stethoscope, } from "lucide-react"; import { cn } from "@duoc-thu/ui"; interface ChatPanelProps { sessionId: string; messages: ChatMessage[]; onMessagesChange: React.Dispatch>; initialQuery?: string; initialQueryToken?: number; onCitationClick?: (citation: Citation, index: number, allCitations: Citation[]) => void; onCitationsLoaded?: (citations: Citation[]) => void; activeCitationIndex?: number | null; monographPicker?: MonographPickerState | null; onMonographChange?: (picker: MonographPickerState | null) => void; onToggleSection?: (sectionKey: string) => void; className?: string; } interface SectionTextResponse { drug_id: string; section_key: string; section_title: string | null; parts: Array<{ part_index: number | null; text: string; is_quarantined: boolean; printed_page_start: number | null; printed_page_end: number | null; physical_page: number | null; }>; } const MONOGRAPH_DISCLAIMER = "Nội dung nguyên văn được lấy từ Dược thư Quốc gia Việt Nam 2018, phục vụ tra cứu chuyên môn và không thay thế chỉ định của bác sĩ hoặc dược sĩ lâm sàng."; const QUICK_SECTION_KEYS = [ "chi_dinh", "lieu_luong_va_cach_dung", "chong_chi_dinh", "than_trong", ]; // The client must never be the thing that gives up first. // // The backend's own per-request budget is 40s (`max_wall_clock_ms` in // `apps/ai-service/config.py`), and that budget is only checked *between* // model calls — `rag/budget.py` says so explicitly: it cannot cancel a boto3 // call already in flight, which is separately bounded by `read_timeout=20` // in `adapters/bedrock_converse.py`. So the backend's real worst case is // ~40s + one in-flight call ≈ 60s, and anything below that truncates work // the server was still legitimately doing. // // Measured against production 2026-08-11 (n=8, sequential, one user): // 6.2 / 6.4 / 8.4 / 10.9 / 12.4 / 21.7 / 25.1 / 40.3 seconds. A 25s limit // cuts off 2 of those 8, including the 25.1s case, which had returned a // correct grounded answer with 2 citations. const REQUEST_TIMEOUT_MS = 65_000; // A single spinner for a minute reads as a hang, so the wait is made // legible rather than merely longer. This is a stopgap for the real fix // (streaming verified claims as they land); it does not make the request // faster, it only stops it looking broken. const SLOW_REQUEST_NOTICE_MS = 15_000; const STARTER_QUESTIONS = [ { category: "Chỉ Định", query: "Levetiracetam được chỉ định trong những trường hợp nào?", icon: Pill, }, { category: "Chống Chỉ Định", query: "Chống chỉ định của Metformin là gì?", icon: Stethoscope, }, { category: "ADR Theo Tần Suất", query: "Tác dụng không mong muốn của Zolpidem là gì?", icon: Activity, }, { category: "Thời Kỳ Mang Thai", query: "Có thể dùng Fluoxetin trong thời kỳ mang thai không?", icon: Zap, }, ]; export function ChatPanel({ sessionId, messages, onMessagesChange: setMessages, initialQuery, initialQueryToken, onCitationClick, onCitationsLoaded, activeCitationIndex = null, monographPicker, onMonographChange, onToggleSection, className, }: ChatPanelProps) { const { resolvedTheme } = useTheme(); const [isLoading, setIsLoading] = useState(false); const [elapsedMs, setElapsedMs] = useState(0); const [error, setError] = useState(null); const [responseMode, setResponseMode] = useState<"ai" | "monograph">("ai"); const messagesEndRef = useRef(null); const abortControllerRef = useRef(null); const initialQuerySentRef = useRef(undefined); const stopRequestedRef = useRef(false); const scrollToBottom = () => { messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }); }; useEffect(() => { scrollToBottom(); }, [messages, isLoading]); const handleSendMessage = async (userText: string) => { if (!userText.trim() || isLoading) return; setError(null); const userMsg: ChatMessage = { id: `user-${Date.now()}`, role: "user", content: userText, createdAt: new Date().toISOString(), }; setMessages((prev) => [...prev, userMsg]); setIsLoading(true); stopRequestedRef.current = false; abortControllerRef.current = new AbortController(); const timeoutId = window.setTimeout(() => { abortControllerRef.current?.abort(); }, REQUEST_TIMEOUT_MS); setElapsedMs(0); const startedAt = Date.now(); const tickId = window.setInterval(() => { setElapsedMs(Date.now() - startedAt); }, 1000); try { const res = await fetch("/api/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ content: userText, conversationId: sessionId, responseMode, }), signal: abortControllerRef.current.signal, }); if (!res.ok) { throw new Error(`Upstream returned status ${res.status}`); } const data: SendMessageResponse = await res.json(); let assistantMsg = data.message; if ( assistantMsg.reason === "select_drug_sections" && assistantMsg.resolvedDrugId && !assistantMsg.resolvedDrugId.includes(",") ) { const drugId = assistantMsg.resolvedDrugId; const [sectionsResponse, suggestionResponse] = await Promise.all([ fetch(`/api/sections?drug_id=${encodeURIComponent(drugId)}`, { cache: "no-store", signal: abortControllerRef.current.signal, }), fetch(`/api/suggest?q=${encodeURIComponent(userText)}`, { cache: "no-store", signal: abortControllerRef.current.signal, }), ]); if (!sectionsResponse.ok) { throw new Error("section_list_unavailable"); } const rawSections = (await sectionsResponse.json()) as { sections?: Array<{ section_key: string; section_title: string }>; }; const suggestionData = suggestionResponse.ok ? ((await suggestionResponse.json()) as { suggestions?: string[] }) : {}; const sections: DrugSectionOption[] = (rawSections.sections ?? []).map( (section) => ({ sectionKey: section.section_key, sectionTitle: section.section_title, }) ); const drugName = suggestionData.suggestions?.[0] ?? userText.trim(); const picker: MonographPickerState = { drugId, drugName, sections, selectedSectionKeys: [], }; assistantMsg = { ...assistantMsg, content: `Chuyên luận ${drugName} có ${sections.length} mục. ` + "Chọn các mục cần xem ở cột bên phải rồi nhấn Gửi tra cứu — " + "nếu không chọn mục nào, hệ thống sẽ hiển thị toàn bộ.", sectionOptions: sections, }; onMonographChange?.(picker); } setMessages((prev) => [...prev, assistantMsg]); if (assistantMsg.citations && assistantMsg.citations.length > 0) { onCitationsLoaded?.(assistantMsg.citations); } } catch (err: any) { if (err.name === "AbortError") { setError( stopRequestedRef.current ? "Đã dừng chờ trên giao diện. Tác vụ đang chạy có thể cần vài giây để kết thúc an toàn." // Describes the timing cause rather than suggesting the // question needs rewording, which rephrasing would not fix. : `Hệ thống xử lý quá ${Math.round( REQUEST_TIMEOUT_MS / 1000 )} giây nên đã dừng yêu cầu này. Vui lòng bấm gửi lại.` ); return; } setError("Không thể kết nối đến máy chủ AI Service. Vui lòng kiểm tra lại dịch vụ backend."); } finally { window.clearTimeout(timeoutId); window.clearInterval(tickId); setElapsedMs(0); setIsLoading(false); abortControllerRef.current = null; } }; const handleSubmitMonograph = async () => { if (!monographPicker || isLoading) return; const selected = monographPicker.selectedSectionKeys.length ? monographPicker.sections.filter((section) => monographPicker.selectedSectionKeys.includes(section.sectionKey) ) : monographPicker.sections; if (selected.length === 0) { setError("Chuyên luận này chưa có mục văn bản để hiển thị."); return; } const label = monographPicker.selectedSectionKeys.length ? selected.map((section) => section.sectionTitle).join(", ") : "Toàn bộ chuyên luận"; const userMsg: ChatMessage = { id: `user-monograph-${Date.now()}`, role: "user", content: `${monographPicker.drugName} — ${label}`, createdAt: new Date().toISOString(), }; setMessages((prev) => [...prev, userMsg]); setError(null); setIsLoading(true); stopRequestedRef.current = false; abortControllerRef.current = new AbortController(); const timeoutId = window.setTimeout( () => abortControllerRef.current?.abort(), 45_000 ); try { const responses = await Promise.all( selected.map(async (section) => { const response = await fetch( `/api/section-text?drug_id=${encodeURIComponent( monographPicker.drugId )}§ion_key=${encodeURIComponent(section.sectionKey)}`, { cache: "no-store", signal: abortControllerRef.current!.signal } ); if (!response.ok) throw new Error("section_text_unavailable"); return (await response.json()) as SectionTextResponse; }) ); const citations: Citation[] = []; const blocks: AnswerBlock[] = []; for (const response of responses) { const claims: AnswerBlock["claims"] = []; for (const [index, part] of response.parts.entries()) { if ( part.printed_page_start == null || part.printed_page_end == null || part.physical_page == null ) { throw new Error("section_provenance_missing"); } const chunkId = `${response.drug_id}__${response.section_key}__${ part.part_index ?? index }`; citations.push({ chunkId, drugName: monographPicker.drugName.toUpperCase(), sectionType: response.section_key, sourceDocument: "Dược thư Quốc gia Việt Nam 2018", sourcePageRange: [part.printed_page_start, part.printed_page_end], physicalPage: part.physical_page, snippet: part.text, isQuarantined: part.is_quarantined, quarantineNotice: part.is_quarantined ? "Mục này có bảng hoặc công thức cần đối chiếu trực tiếp trang PDF gốc." : undefined, }); claims.push({ text: part.text, sourceIds: [chunkId] }); } blocks.push({ title: response.section_title ?? selected.find((item) => item.sectionKey === response.section_key) ?.sectionTitle ?? response.section_key, kind: "fact_list", claims, }); } const assistantMsg: ChatMessage = { id: `monograph-${Date.now()}`, role: "assistant", content: `Nguyên văn ${selected.length} mục của ${monographPicker.drugName}.`, citations, disclaimer: MONOGRAPH_DISCLAIMER, decision: "answerable", reason: "verbatim_sections", grounded: true, generated: false, resolvedDrugId: monographPicker.drugId, blocks, answerMode: "detailed", answerPlan: { verbosity: "detailed", layout: "bullet_list", reasoningMode: "direct_lookup", showHeading: true, needsWarning: false, }, createdAt: new Date().toISOString(), }; setMessages((prev) => [...prev, assistantMsg]); onCitationsLoaded?.(citations); } catch (err: any) { setError( err?.name === "AbortError" ? "Đã dừng tải chuyên luận." : "Không thể tải đầy đủ nguyên văn các mục đã chọn. Vui lòng thử lại." ); } finally { window.clearTimeout(timeoutId); setIsLoading(false); abortControllerRef.current = null; } }; const handleStop = () => { if (abortControllerRef.current) { stopRequestedRef.current = true; abortControllerRef.current.abort(); } }; const handleResponseModeChange = (mode: "ai" | "monograph") => { setResponseMode(mode); if (mode === "ai") { onMonographChange?.(null); } }; useEffect(() => { return () => abortControllerRef.current?.abort(); }, []); useEffect(() => { // Guard against firing twice for the same query: React 18 Strict Mode // (dev only) runs this effect setup twice on mount, and with no guard // that sent every quick-prompt click as two identical live requests // (found live 2026-08-07: duplicate "Chỉ định & Tác dụng không mong // muốn của Aspirin" turns in the trace). The ref persists across the // Strict Mode replay, so the second invocation for the same // `initialQuery` is a no-op; a genuinely new query still sends once. if ( initialQuery && initialQueryToken !== undefined && initialQuerySentRef.current !== initialQueryToken ) { initialQuerySentRef.current = initialQueryToken; handleSendMessage(initialQuery); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [initialQuery, initialQueryToken]); // Empty state renderer per theme const renderEmptyState = () => { if (resolvedTheme === "light") { return (
Daylight Clinical Intelligence (DTQGVN 2018)

Tra Cứu Dược Thư Quốc Gia Việt Nam

Tra cứu 684 chuyên luận Dược thư Quốc gia Việt Nam 2018 với căn cứ theo trang in. Khi cần, bác sĩ có thể tiếp tục trao đổi để làm rõ dữ kiện và đối chiếu với bối cảnh lâm sàng.

{STARTER_QUESTIONS.map((q, idx) => { const Icon = q.icon; return ( ); })}
); } if (resolvedTheme === "glass") { return (
Heavy Glass Liquid Intelligence OS

Hệ Thống Trí Tuệ Y Tế Spatial

Không gian tra cứu đa tầng kính với hiệu ứng Citation Beam liên kết trực tiếp khẳng định lâm sàng đến trang sách gốc Dược thư 2018.

{STARTER_QUESTIONS.map((q, idx) => { const Icon = q.icon; return ( ); })}
); } // Default Dark mode return (
Night Laboratory Intelligence Workspace

Trợ Lý Tra Cứu Dược Thư QGVN

Hệ thống phân tích & tra cứu Dược thư Quốc gia Việt Nam 2018. Đặt câu hỏi lâm sàng để nhận phân tích có căn cứ trích dẫn chính xác.

{STARTER_QUESTIONS.map((q, idx) => { const Icon = q.icon; return ( ); })}
); }; return (
{/* Citation Beam Overlay for Signature Interaction */} {/* Messages Workspace List */}
{messages.length === 0 ? ( renderEmptyState() ) : ( messages.map((msg, msgIdx) => { // Retry must resend the ORIGINAL user question, not this // bubble's own text — for an assistant bubble, `msg.content` is // the answer/error text itself, so resending it fed the error // message back in as if it were the next question (found live // 2026-08-07: a trace row where the query text WAS literally // "Dịch vụ đang gặp sự cố tạm thời..."). Walk back to the // nearest preceding user turn instead. const retryQuery = msg.role === "assistant" ? [...messages.slice(0, msgIdx)].reverse().find((m) => m.role === "user")?.content : undefined; return ( onCitationClick?.(citation, idx, allCitations) } activeCitationIndex={activeCitationIndex} onRetry={retryQuery ? () => handleSendMessage(retryQuery) : undefined} onQuickReply={ msgIdx === messages.length - 1 && msg.decision === "clarify" && !isLoading ? (text) => handleSendMessage(text) : undefined } /> {msg.role === "assistant" && msg.sectionOptions && msg.sectionOptions.length > 0 && (
{QUICK_SECTION_KEYS.flatMap((key) => { const section = msg.sectionOptions?.find( (item) => item.sectionKey === key ); if (!section) return []; const selected = monographPicker?.selectedSectionKeys.includes(key) ?? false; return [ , ]; })}
)} {msg.role === "assistant" && msg.traceId && msg.reason !== "select_drug_sections" && !msg.traceId.startsWith("fallback-") && ( )}
); }) )} {/* Loading Indicator */} {isLoading && (

Đang truy xuất Dược thư QGVN 2018... {elapsedMs >= 1000 && ` ${Math.floor(elapsedMs / 1000)}s`}

{elapsedMs >= SLOW_REQUEST_NOTICE_MS ? "Câu hỏi tra cả mục nên cần thêm thời gian đối chiếu nguồn — vẫn đang xử lý." : "Đang phân tích chuyên luận & xác thực Entailment"}

)} {/* Error Notification */} {error && (
{error}
)}
{/* Fixed Composer Bottom Bar */}
onMonographChange?.(null)} onSubmitMonograph={handleSubmitMonograph} responseMode={responseMode} onResponseModeChange={handleResponseModeChange} />
); }