"use client"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { AlertCircle, Loader2 } from "lucide-react"; import { useTranslation } from "react-i18next"; import { useChatAutoScroll } from "@/hooks/useChatAutoScroll"; import { TurnNavigator } from "@/components/chat/home/TurnNavigator"; import { getPartnerGroupWhiteboard, type PartnerGroup, type PartnerGroupMessage, type WhiteboardEntry, } from "@/lib/partner-groups-api"; import GroupSidePanel, { type PanelTab, type TraceFocus, } from "./GroupSidePanel"; import GroupComposer, { type QuotedSpeech } from "./GroupComposer"; import GroupEmptyState from "./GroupEmptyState"; import GroupRound from "./GroupRound"; import { buildGroupOutline } from "./outline"; import { useGroupSession } from "./useGroupSession"; /** * The group discussion surface. * * This component only wires things together: session state lives in * ``useGroupSession``, a round renders itself, and the composer owns mention * resolution. Keeping the shell thin is what makes the round/seat model * readable — the interesting logic is not buried in JSX. */ export default function PartnerGroupChat({ group, sessionKey, panelOpen, onOpenPanel, onClosePanel, onMessagesChange, embedded = false, consultationActive = false, }: { embedded?: boolean; consultationActive?: boolean; group: PartnerGroup; /** Which discussion thread is open; owned by the page header's picker. */ sessionKey: string; /** Open state is owned by the page header, which holds the toggle. */ panelOpen: boolean; onOpenPanel: () => void; onClosePanel: () => void; /** Lift the settled transcript to page-level export controls. */ onMessagesChange?: (messages: PartnerGroupMessage[]) => void; }) { const { t } = useTranslation(); const [quote, setQuote] = useState(null); const [board, setBoard] = useState([]); const [panelTab, setPanelTab] = useState("reasoning"); const [traceFocus, setTraceFocus] = useState(null); const { messages, rounds, reportConsultationActivity, running, progress, connected, loading, error, setError, pendingActions, send, actOnInvocation, askPeer, summarizeRound, cancel, } = useGroupSession(group, sessionKey); // Match direct Partner chat: export only persisted messages, never a // token-by-token draft. Clear the lifted transcript while another thread // is loading so the header cannot download the previous discussion. useEffect(() => { onMessagesChange?.(loading ? [] : messages); }, [loading, messages, onMessagesChange]); const draftRef = useRef(false); const lastInteraction = useRef(0); const reportInteraction = useCallback(() => { if (!consultationActive || Date.now() - lastInteraction.current < 200) return; lastInteraction.current = Date.now(); reportConsultationActivity(draftRef.current, true); }, [consultationActive, reportConsultationActivity]); const reportDraft = useCallback((hasDraft: boolean) => { const changed = draftRef.current !== hasDraft; draftRef.current = hasDraft; if (consultationActive) reportConsultationActivity(hasDraft, changed); }, [consultationActive, reportConsultationActivity]); useEffect(() => { if (!consultationActive || !connected) return; // A heartbeat renews the draft lease but does not count as user activity. const renew = () => reportConsultationActivity(draftRef.current, false); renew(); const timer = setInterval(renew, 2000); return () => clearInterval(timer); }, [consultationActive, connected, reportConsultationActivity]); const lastSeat = rounds[rounds.length - 1]?.seats.slice(-1)[0]; const seatCount = useMemo( () => rounds.reduce((total, round) => total + round.seats.length, 0), [rounds], ); const eventCount = useMemo( () => rounds.reduce( (total, round) => total + round.seats.reduce((sum, seat) => sum + seat.events.length, 0), 0, ), [rounds], ); const outline = useMemo(() => buildGroupOutline(rounds), [rounds]); const { containerRef, handleScroll, scrollToBottom } = useChatAutoScroll({ hasMessages: rounds.length > 0, isStreaming: running, composerHeight: 0, messageCount: seatCount, lastMessageContent: lastSeat?.message?.content ?? lastSeat?.streamed, lastEventCount: eventCount, }); /** Scroll a round into view and flash it, mirroring product chat. */ const jumpToRound = useCallback( (key: string) => { const container = containerRef.current; const target = container?.querySelector( `[data-turn-key="${key}"]`, ); if (!container || !target) return; const offset = target.getBoundingClientRect().top - container.getBoundingClientRect().top; container.scrollTo({ top: container.scrollTop + offset - 24, behavior: "smooth", }); const bubble = target.querySelector("[data-turn-bubble]") ?? target; bubble.classList.remove("turn-flash"); // Reflow so the animation restarts when the same tick is clicked twice. void bubble.offsetWidth; bubble.classList.add("turn-flash"); }, [containerRef], ); /** * Hand one speaker's point to a peer. * * Phrased in the requester's own voice because the backend publishes it as * " asks you directly in the Group: …" — and kept short so the * quoted excerpt does not crowd out the actual question. */ const handleAskPeer = useCallback( (requesterId: string, targetId: string, content: string) => { const excerpt = content.trim().slice(0, 400); const question = t( "Here is the point I just made: “{{excerpt}}”. What is your take on it?", { excerpt }, ); const ok = askPeer(requesterId, targetId, question); if (!ok) setError(t("Group is reconnecting")); return ok; }, [askPeer, setError, t], ); const refreshBoard = useCallback(() => { void getPartnerGroupWhiteboard(group.group_id) .then(setBoard) .catch(() => setBoard([])); }, [group.group_id]); useEffect(() => { if (panelOpen && panelTab === "context") refreshBoard(); }, [panelOpen, panelTab, refreshBoard, running]); const openTrace = useCallback( (turnId: string, partnerId: string) => { setPanelTab("reasoning"); setTraceFocus({ turnId, partnerId }); onOpenPanel(); }, [onOpenPanel], ); return (
{ if (event.buttons) reportInteraction() }} onKeyDownCapture={reportInteraction} >
{/* The rail is an absolutely-positioned sibling of the scrollport, so the two share this wrapper and nothing else lives in it. */}
{loading ? (
) : rounds.length === 0 ? ( ) : ( rounds.map((round) => ( actOnInvocation(id, "approve")} onReject={(id) => actOnInvocation(id, "reject")} onQuote={setQuote} onOpenTrace={openTrace} onAskPeer={handleAskPeer} onSummarize={summarizeRound} /> )) )} {error ? ( // The raw backend reason is kept — it is what makes a failure // diagnosable — but it is framed so the user knows what it means.

{t("This round could not finish")}

{error}

) : null}
scrollToBottom("smooth")} />
setQuote(null)} onSend={(content, mentions) => { const ok = send(content, mentions); if (!ok) setError(t("Group is reconnecting")); else setError(""); return ok; }} onCancel={cancel} />
); }