import { forwardRef, type ReactNode, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, } from "react"; import { ArrowDown } from "lucide-react"; import { useTranslation } from "react-i18next"; import { PromptRail } from "@/components/thread/PromptRail"; import { SubagentThreadMessages, useHasSubagentResults } from "@/components/thread/SubagentTaskResults"; import { DiagramScope } from "@/components/markdown-diagrams/context"; import { ThreadHistoryStatus } from "@/components/thread/ThreadHistoryStatus"; import { isAgentActivityMember } from "@/components/thread/AgentActivityCluster"; import { ThreadCameraController } from "@/components/thread/thread-camera"; import { HISTORY_HOLD_PX, ThreadHistorySpring, type HistoryRevealPhase } from "@/components/thread/thread-history-spring"; import { ThreadMotionCoordinator, type ThreadMotionGeometry, } from "@/components/thread/thread-motion"; import { Button } from "@/components/ui/button"; import { findPromptElement, promptTop, } from "@/components/thread/promptNavigation"; import { cn } from "@/lib/utils"; import type { PromptHistoryNavigation } from "@/hooks/usePromptHistory"; import type { CliAppInfo, McpPresetInfo, RetryStatus, SlashCommand, UIMessage } from "@/lib/types"; export interface ThreadViewportHandle { jumpToUserPrompt: (promptId: string) => void; cancelAutoScroll: () => void; } interface ThreadViewportProps { messages: UIMessage[]; navigation?: PromptHistoryNavigation; temporary?: boolean; isStreaming: boolean; /** Optimistic or canonical start time for the active turn, in unix seconds. */ runStartedAt?: number | null; retryStatus?: RetryStatus | null; composer?: ReactNode; navigationFrame?: HTMLElement | null; emptyState?: ReactNode; initialLoading?: boolean; scrollToBottomSignal?: number; activeTurnId?: string | null; activeTurnStartedHere?: boolean; conversationKey?: string | null; conversationReady?: boolean; showScrollToBottomButton?: boolean; cliApps?: CliAppInfo[]; mcpPresets?: McpPresetInfo[]; slashCommands?: SlashCommand[]; forkBoundaryMessageCount?: number | null; hasMoreBefore?: boolean; loadingOlder?: boolean; olderError?: string | null; userMessageOffset?: number; onLoadOlder?: () => Promise | void; traceDetailScope?: string | null; onLoadTraceDetails?: (refs: string[]) => void | Promise; onOpenFilePreview?: (path: string) => void; onForkFromMessage?: (beforeUserIndex: number) => void; onQuoteSelection?: (text: string) => void; } const NEAR_BOTTOM_PX = 48; const PROMPT_TOP_INSET_PX = 48; const HISTORY_PREFETCH_MIN_PX = 160; const HISTORY_PREFETCH_MAX_PX = 480; const DEFAULT_SCROLL_BUTTON_BOTTOM_PX = 192; const EXTERNAL_COMPOSER_SCROLL_BUTTON_BOTTOM_PX = 16; const SCROLL_BUTTON_COMPOSER_GAP_PX = 16; const SOFT_KEYBOARD_MIN_INSET_PX = 80; const SESSION_HANDOFF_EXIT_DURATION_MS = 80; const SESSION_HANDOFF_ENTER_DURATION_MS = 140; const SESSION_HANDOFF_OPACITY = 0.82; export const INITIAL_HISTORY_WINDOW = 120; export const HISTORY_WINDOW_INCREMENT = 120; interface HistoryScrollAnchor { key: string; offsetTop: number; scrollTop: number; } const THREAD_DISPLAY_UNIT_SELECTOR = "[data-thread-display-unit]"; function promptTopInset(scroller: HTMLElement): number { const padding = Number.parseFloat(getComputedStyle(scroller).scrollPaddingTop); return Number.isFinite(padding) ? padding : PROMPT_TOP_INSET_PX; } function historyPrefetchDistance(scroller: HTMLElement): number { return Math.min( HISTORY_PREFETCH_MAX_PX, Math.max(HISTORY_PREFETCH_MIN_PX, scroller.clientHeight / 2), ); } function visibleHistoryUnit( content: HTMLElement, viewport: DOMRect, ): HTMLElement | null { // Scroll is a hot path. Hit-testing keeps the common case O(1) instead of // forcing layout for every mounted message while the trackpad is moving. if (typeof document.elementsFromPoint === "function" && viewport.height > 0) { const contentBounds = content.getBoundingClientRect(); const left = Math.max(viewport.left, contentBounds.left); const right = Math.min(viewport.right, contentBounds.right); const x = left + Math.max(0, right - left) / 2; const offsets = [1, Math.min(32, viewport.height / 3), viewport.height / 2]; for (const offset of offsets) { for (const target of document.elementsFromPoint(x, viewport.top + offset)) { const unit = target instanceof Element ? target.closest(THREAD_DISPLAY_UNIT_SELECTOR) : null; if (unit && content.contains(unit)) return unit; } } } // Deterministic fallback for pre-layout states, tests, and older browsers. const units = Array.from( content.querySelectorAll(THREAD_DISPLAY_UNIT_SELECTOR), ); return units.find((unit) => { const bounds = unit.getBoundingClientRect(); return bounds.bottom > viewport.top && bounds.top < viewport.bottom; }) ?? units[0] ?? null; } export function windowMessages(messages: UIMessage[], visibleCount: number): UIMessage[] { if (messages.length <= visibleCount) return messages; let start = Math.max(0, messages.length - visibleCount); while ( start > 0 && isAgentActivityMember(messages[start]) && isAgentActivityMember(messages[start - 1]) ) { start -= 1; } return messages.slice(start); } function isKeyboardEditableElement(element: Element | null): element is HTMLElement { if (!(element instanceof HTMLElement)) return false; if (element.isContentEditable) return true; if (element instanceof HTMLTextAreaElement) return true; if (!(element instanceof HTMLInputElement)) return false; return ![ "button", "checkbox", "color", "file", "hidden", "image", "radio", "range", "reset", "submit", ].includes(element.type); } function isThreadDisclosureTarget(target: EventTarget | null): boolean { return target instanceof Element && target.closest("[data-thread-disclosure]") !== null; } function isKeyboardControl(element: Element | null): boolean { return element instanceof HTMLElement && element.closest( "button, a[href], select, [role='button'], [role='menuitem'], [role='option']", ) !== null; } type ThreadScrollDirection = "backward" | "forward"; const KEYBOARD_SCROLL_DIRECTIONS: Readonly< Partial> > = { ArrowUp: "backward", PageUp: "backward", Home: "backward", ArrowDown: "forward", PageDown: "forward", End: "forward", }; function directionFromDelta(deltaY: number): ThreadScrollDirection | null { return deltaY < 0 ? "backward" : deltaY > 0 ? "forward" : null; } function keyboardScrollDirection( event: KeyboardEvent, ): ThreadScrollDirection | null { if (event.key === " ") { return event.shiftKey ? "backward" : "forward"; } return KEYBOARD_SCROLL_DIRECTIONS[event.key] ?? null; } function canScrollInDirection( element: HTMLElement, direction: ThreadScrollDirection | null, ): boolean { switch (direction) { case "backward": return element.scrollTop > 0; case "forward": return ( element.scrollTop < Math.max(0, element.scrollHeight - element.clientHeight) ); default: return false; } } function readSoftKeyboardInsetBottom(container: HTMLElement | null): number { // The touch App shell already fits the visual viewport, including portaled // composers. Keep the existing local inset only for unfitted/native layouts. if (container?.closest("#root.visual-viewport")) return 0; const viewport = window.visualViewport; if (!viewport) return 0; const active = document.activeElement; if (!isKeyboardEditableElement(active) || !container?.contains(active)) return 0; const layoutHeight = window.innerHeight || document.documentElement.clientHeight; const inset = layoutHeight - viewport.height - viewport.offsetTop; return inset >= SOFT_KEYBOARD_MIN_INSET_PX ? Math.ceil(inset) : 0; } function setHistoryPresentation( scroller: HTMLDivElement | null, status: HTMLDivElement | null, slot: HTMLDivElement | null, distance: number, ): void { // A retained inline slot replaces the same amount of presentation travel. const travel = distance - (slot ? HISTORY_HOLD_PX : 0); if (scroller) scroller.style.transform = travel ? `translateY(${travel}px)` : ""; status?.style.setProperty("--history-pull", `${distance}px`); } export const ThreadViewport = forwardRef(function ThreadViewport({ messages: latestMessages, navigation, temporary = false, isStreaming: liveStreaming, runStartedAt = null, retryStatus = null, composer, navigationFrame, emptyState, initialLoading = false, scrollToBottomSignal = 0, activeTurnId: liveTurnId = null, activeTurnStartedHere = false, conversationKey = null, conversationReady = true, showScrollToBottomButton = true, cliApps = [], mcpPresets = [], slashCommands = [], forkBoundaryMessageCount: latestForkBoundary = null, hasMoreBefore: latestHasMoreBefore = false, loadingOlder: latestLoadingOlder = false, olderError: latestOlderError = null, userMessageOffset: latestUserOffset = 0, onLoadOlder: loadLatestOlder, traceDetailScope = null, onLoadTraceDetails, onOpenFilePreview, onForkFromMessage, onQuoteSelection, }, ref) { const { t } = useTranslation(); const historyWindow = navigation?.window; const messages = historyWindow?.messages ?? latestMessages; const isStreaming = !historyWindow && liveStreaming; const activeTurnId = historyWindow ? null : liveTurnId; const forkBoundaryMessageCount = historyWindow ? historyWindow.forkBoundaryMessageCount : latestForkBoundary; const hasMoreBefore = historyWindow?.hasMoreBefore ?? latestHasMoreBefore; const loadingOlder = historyWindow ? navigation!.operation === "older" && navigation!.loading : latestLoadingOlder; const olderError = historyWindow ? navigation!.operation === "older" ? navigation!.error : null : latestOlderError; const userMessageOffset = historyWindow?.userMessageOffset ?? latestUserOffset; const onLoadOlder = historyWindow ? navigation!.older : loadLatestOlder; const scrollRef = useRef(null); const viewportFrameRef = useRef(null); const contentRef = useRef(null); const messageRegionRef = useRef(null); const messageContentRef = useRef(null); const emptyStateRef = useRef(null); const composerDockRef = useRef(null); const bottomRef = useRef(null); const lastConversationKeyRef = useRef(conversationKey); const conversationHandoffPendingRef = useRef(false); const conversationHandoffAnimationRef = useRef(null); const pendingConversationScrollRef = useRef(true); const pendingPromptJumpRef = useRef(null); const restoreScrollAfterPrependRef = useRef<{ height: number; top: number } | null>(null); const historyScrollAnchorRef = useRef(null); const previousLoadingOlderRef = useRef(loadingOlder); const composerDockHeightRef = useRef(0); const [atBottom, setAtBottom] = useState(true); const [atHistoryTop, setAtHistoryTop] = useState(false); const [historyPhase, setHistoryPhase] = useState("hidden"); const historyPhaseRef = useRef(historyPhase); const [historySlotKey, setHistorySlotKey] = useState(null); const historySlotCompleted = previousLoadingOlderRef.current && !loadingOlder && !olderError && historySlotKey !== null; const retainedHistorySlotKey = historySlotCompleted ? null : historySlotKey; const [showHistoryExhausted, setShowHistoryExhausted] = useState(false); const historySlotRef = useRef(null); const historyInputRef = useRef<"touch" | "other">("other"); const historyTouchRef = useRef<{ lastY: number; startX: number; startY: number; pulling: boolean; horizontal: boolean; } | null>(null); const historyDistanceRef = useRef(0); const historyStatusRef = useRef(null); const historySpringRef = useRef(null); if (historySpringRef.current === null) { historySpringRef.current = new ThreadHistorySpring({ onPhaseChange: (phase) => { const previous = historyPhaseRef.current; historyPhaseRef.current = phase; setHistoryPhase(phase); if (phase === "hidden" && previous === "feedback") setShowHistoryExhausted(false); }, onUpdate: (distance) => { historyDistanceRef.current = distance; setHistoryPresentation(messageRegionRef.current, historyStatusRef.current, historySlotRef.current, distance); }, }); } const setMessageRegion = useCallback((element: HTMLDivElement | null) => { // React can reuse this div for the empty state; release imperative styles with the ref. messageRegionRef.current?.style.removeProperty("transform"); messageRegionRef.current = element; setHistoryPresentation(element, historyStatusRef.current, historySlotRef.current, historyDistanceRef.current); }, []); const setHistoryStatus = useCallback((element: HTMLDivElement | null) => { historyStatusRef.current = element; setHistoryPresentation(messageRegionRef.current, element, historySlotRef.current, historyDistanceRef.current); }, []); const setHistorySlot = useCallback((element: HTMLDivElement | null) => { historySlotRef.current = element; setHistoryPresentation(messageRegionRef.current, historyStatusRef.current, element, historyDistanceRef.current); }, []); const [composerDockHeight, setComposerDockHeight] = useState(0); const [keyboardInsetBottom, setKeyboardInsetBottom] = useState(0); const [hasVerticalOverflow, setHasVerticalOverflow] = useState(false); const [visibleMessageCount, setVisibleMessageCount] = useState(INITIAL_HISTORY_WINDOW); const threadMotionRef = useRef(null); if (threadMotionRef.current === null) { const camera = new ThreadCameraController(() => scrollRef.current); threadMotionRef.current = new ThreadMotionCoordinator({ camera, measure: (promptId) => { const scrollEl = scrollRef.current; const composerDock = composerDockRef.current; if (!scrollEl) return null; const composerHeight = composerDock ? composerDock.getBoundingClientRect().height || composerDock.offsetHeight : 0; const prompt = promptId ? findPromptElement(scrollEl, promptId) : null; const scrollHeight = scrollEl.scrollHeight; const clientHeight = scrollEl.clientHeight; const maxScrollTop = Math.max(0, scrollHeight - clientHeight); return { scrollTop: scrollEl.scrollTop, scrollHeight, clientHeight, maxScrollTop, composerHeight, promptTop: prompt ? Math.min( maxScrollTop, Math.max(0, promptTop(scrollEl, prompt) - promptTopInset(scrollEl)), ) : null, }; }, onGeometry: (geometry: ThreadMotionGeometry) => { if (Math.abs(composerDockHeightRef.current - geometry.composerHeight) >= 1) { composerDockHeightRef.current = geometry.composerHeight; setComposerDockHeight(geometry.composerHeight); } const nextOverflow = geometry.scrollHeight > geometry.clientHeight + 1; setHasVerticalOverflow((current) => current === nextOverflow ? current : nextOverflow, ); }, onAutoFollow: () => setAtBottom(true), }); } const hasTaskResults = useHasSubagentResults(); const hasMessages = messages.length > 0 || (hasTaskResults && conversationReady); const hasThreadLayout = hasMessages || initialLoading; useLayoutEffect(() => { scrollRef.current = hasMessages ? messageRegionRef.current : viewportFrameRef.current; }, [hasMessages]); const visibleMessages = useMemo( () => windowMessages(messages, visibleMessageCount), [messages, visibleMessageCount], ); const hiddenMessageCount = messages.length - visibleMessages.length; const historyExhausted = !hasMoreBefore && hiddenMessageCount === 0; const hiddenUserMessageCount = userMessageOffset + (hiddenMessageCount > 0 ? messages.slice(0, hiddenMessageCount).filter( (message) => message.role === "user" && message.deliveryStatus !== "failed", ).length : 0); const visibleForkBoundaryMessageCount = forkBoundaryMessageCount !== null && forkBoundaryMessageCount > hiddenMessageCount ? forkBoundaryMessageCount - hiddenMessageCount : null; const hasComposer = composer !== null && composer !== undefined; const scrollButtonBottom = keyboardInsetBottom + (composerDockHeight > 0 ? composerDockHeight + SCROLL_BUTTON_COMPOSER_GAP_PX : hasComposer ? DEFAULT_SCROLL_BUTTON_BOTTOM_PX : EXTERNAL_COMPOSER_SCROLL_BUTTON_BOTTOM_PX); const scrollViewportStyle = keyboardInsetBottom > 0 ? { bottom: keyboardInsetBottom } : undefined; const yieldCameraToUser = useCallback(() => { threadMotionRef.current?.takeUserControl(); }, []); const captureHistoryScrollAnchor = useCallback(() => { const scroller = scrollRef.current; const content = messageContentRef.current; if (!scroller || !content) { historyScrollAnchorRef.current = null; return false; } const viewport = scroller.getBoundingClientRect(); const element = visibleHistoryUnit(content, viewport); const key = element?.dataset.threadDisplayUnit; if (!element || !key) { historyScrollAnchorRef.current = null; return false; } historyScrollAnchorRef.current = { key, scrollTop: scroller.scrollTop, // Normalize out the reveal lease, even when reading above its inline slot. offsetTop: element.getBoundingClientRect().top - viewport.top - (historySlotRef.current ? HISTORY_HOLD_PX : 0), }; return true; }, []); const reconcileHistoryScrollAnchor = useCallback(() => { const scroller = scrollRef.current; const content = messageContentRef.current; const anchor = historyScrollAnchorRef.current; if (!scroller || !content || !anchor) return false; const element = Array.from( content.querySelectorAll("[data-thread-display-unit]"), ).find((candidate) => candidate.dataset.threadDisplayUnit === anchor.key); if (!element) { historyScrollAnchorRef.current = null; return false; } const nextOffset = element.getBoundingClientRect().top - scroller.getBoundingClientRect().top - (historySlotRef.current ? HISTORY_HOLD_PX : 0); const delta = nextOffset - anchor.offsetTop; if (Math.abs(delta) < 0.5) return true; const maxScrollTop = Math.max(0, scroller.scrollHeight - scroller.clientHeight); const nextTop = Math.min(maxScrollTop, Math.max(0, scroller.scrollTop + delta)); threadMotionRef.current?.jumpTo(nextTop); anchor.scrollTop = scroller.scrollTop; return true; }, []); const resetHistoryHeader = useCallback(() => { setHistorySlotKey(null); historySpringRef.current?.reset(); }, []); const holdHistoryHeader = useCallback(() => { // A request at a new boundary supersedes the old slot. Mid-page retry // keeps its original boundary, never a hit-tested answer or activity row. if (!historySlotRef.current || (scrollRef.current && scrollRef.current.scrollTop <= 1)) { const unit = messageContentRef.current?.querySelector(THREAD_DISPLAY_UNIT_SELECTOR); if (unit?.dataset.threadDisplayUnit) setHistorySlotKey(unit.dataset.threadDisplayUnit); } historySpringRef.current?.hold(); }, []); useLayoutEffect(() => { // Replaced history windows cannot retain a slot for an unmounted boundary. if (retainedHistorySlotKey && !historySlotRef.current) resetHistoryHeader(); }, [retainedHistorySlotKey, resetHistoryHeader, visibleMessages]); const scrollToBottomNow = useCallback((smooth = false) => { historyScrollAnchorRef.current = null; resetHistoryHeader(); const el = scrollRef.current; const marker = bottomRef.current; const behavior: ScrollBehavior = smooth ? "smooth" : "auto"; if (el) { const top = Math.max(0, el.scrollHeight - el.clientHeight); if (smooth) { threadMotionRef.current?.navigateLatestTo(top); } else { threadMotionRef.current?.jumpTo(top); } } else if (marker) { marker.scrollIntoView({ block: "end", behavior }); } setAtBottom(true); }, [resetHistoryHeader]); const scrollToBottom = useCallback( (smooth = false, options?: { force?: boolean }) => { const force = options?.force ?? false; if (!force && threadMotionRef.current?.isAutoFollowPaused()) return; if (!smooth) threadMotionRef.current?.resumeAutoFollow(); scrollToBottomNow(smooth); }, [scrollToBottomNow], ); const loadEarlierMessages = useCallback(() => { if (loadingOlder || navigation?.loading) return; const el = scrollRef.current; if (el) { if (captureHistoryScrollAnchor()) { restoreScrollAfterPrependRef.current = null; } else { restoreScrollAfterPrependRef.current = { height: el.scrollHeight, top: el.scrollTop, }; } } threadMotionRef.current?.takeUserControl(); setAtBottom(false); if (hiddenMessageCount > 0) { setVisibleMessageCount((count) => Math.min(messages.length, count + HISTORY_WINDOW_INCREMENT), ); return; } if (hasMoreBefore && onLoadOlder) { holdHistoryHeader(); setVisibleMessageCount((count) => count + HISTORY_WINDOW_INCREMENT); void onLoadOlder(); } }, [ captureHistoryScrollAnchor, hasMoreBefore, hiddenMessageCount, holdHistoryHeader, loadingOlder, messages.length, navigation?.loading, onLoadOlder, ]); const maybeLoadEarlierFromScroll = useCallback(() => { const el = scrollRef.current; if (!el || !hasMessages || pendingConversationScrollRef.current) return; if (!threadMotionRef.current?.isBrowsingHistory()) return; if (el.scrollTop > historyPrefetchDistance(el)) return; if (hiddenMessageCount <= 0 && (historyInputRef.current === "touch" || el.scrollTop > 1)) return; if (hiddenMessageCount <= 0 && (!hasMoreBefore || olderError)) return; loadEarlierMessages(); }, [hasMessages, hasMoreBefore, hiddenMessageCount, loadEarlierMessages, olderError]); const navigateToVisiblePrompt = useCallback((promptId: string) => { const scrollEl = scrollRef.current; const prompt = scrollEl ? findPromptElement(scrollEl, promptId) : null; if (!scrollEl || !prompt) return false; historyScrollAnchorRef.current = null; resetHistoryHeader(); setAtBottom(false); threadMotionRef.current?.navigateHistoryToPrompt(promptId); return true; }, [resetHistoryHeader]); const jumpToUserPrompt = useCallback((promptId: string) => { // A local destination also supersedes an in-flight remote jump. navigation?.cancel(); pendingPromptJumpRef.current = null; if (navigateToVisiblePrompt(promptId)) return; if (navigation?.prompts.some((prompt) => prompt.id === promptId && prompt.cursor)) { threadMotionRef.current?.takeUserControl(); navigation.jump(promptId); return; } const localMessages = historyWindow ? latestMessages : messages; const index = localMessages.findIndex((message) => message.id === promptId); if (index < 0) return; if (historyWindow) navigation?.latest(); threadMotionRef.current?.takeUserControl(); pendingPromptJumpRef.current = promptId; setAtBottom(false); setVisibleMessageCount((count) => Math.max(count, localMessages.length - index)); }, [historyWindow, latestMessages, messages, navigateToVisiblePrompt, navigation]); useLayoutEffect(() => { if (!navigation?.target) return; historyScrollAnchorRef.current = null; restoreScrollAfterPrependRef.current = null; pendingConversationScrollRef.current = false; pendingPromptJumpRef.current = navigation.target.id; threadMotionRef.current?.takeUserControl(); setAtBottom(false); const index = messages.findIndex((message) => message.id === navigation.target!.id); setVisibleMessageCount(Math.max(INITIAL_HISTORY_WINDOW, messages.length - Math.max(0, index))); }, [navigation?.target]); useEffect(() => { if (activeTurnStartedHere && liveTurnId) navigation?.latest(); }, [activeTurnStartedHere, liveTurnId, navigation?.latest]); const cancelAutoScroll = useCallback(() => { threadMotionRef.current?.takeUserControl(); }, []); useImperativeHandle( ref, () => ({ jumpToUserPrompt, cancelAutoScroll, }), [cancelAutoScroll, jumpToUserPrompt], ); useLayoutEffect(() => { const updateKeyboardInset = () => { const composerDock = composerDockRef.current; const next = readSoftKeyboardInsetBottom(composerDock); const active = document.activeElement; const composerFocused = hasMessages && isKeyboardEditableElement(active) && Boolean(composerDock?.contains(active)); setKeyboardInsetBottom((current) => Math.abs(current - next) < 1 ? current : next, ); if (composerFocused) { // Focusing the composer establishes a new reference frame at the // latest message. This is one immediate positioning command; viewport // events may issue a fresh command, but no command survives into a // later render as a train of retry frames. scrollToBottom(false, { force: true }); } }; updateKeyboardInset(); const viewport = window.visualViewport; viewport?.addEventListener("resize", updateKeyboardInset); viewport?.addEventListener("scroll", updateKeyboardInset); window.addEventListener("resize", updateKeyboardInset); document.addEventListener("focusin", updateKeyboardInset); document.addEventListener("focusout", updateKeyboardInset); return () => { viewport?.removeEventListener("resize", updateKeyboardInset); viewport?.removeEventListener("scroll", updateKeyboardInset); window.removeEventListener("resize", updateKeyboardInset); document.removeEventListener("focusin", updateKeyboardInset); document.removeEventListener("focusout", updateKeyboardInset); }; }, [hasMessages, scrollToBottom]); useEffect(() => { if (scrollToBottomSignal <= 0) return; scrollToBottom(false, { force: true }); }, [scrollToBottomSignal, scrollToBottom]); useLayoutEffect(() => { if (lastConversationKeyRef.current === conversationKey) return; lastConversationKeyRef.current = conversationKey; historyTouchRef.current = null; historyInputRef.current = "other"; resetHistoryHeader(); conversationHandoffAnimationRef.current?.cancel(); conversationHandoffAnimationRef.current = null; conversationHandoffPendingRef.current = true; pendingConversationScrollRef.current = true; historyScrollAnchorRef.current = null; restoreScrollAfterPrependRef.current = null; threadMotionRef.current?.reset(); setAtBottom(true); setShowHistoryExhausted(false); setVisibleMessageCount(INITIAL_HISTORY_WINDOW); const surface = hasMessages ? messageRegionRef.current : emptyStateRef.current; const reduceMotion = typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches; if (!surface || reduceMotion || typeof surface.animate !== "function") return; conversationHandoffAnimationRef.current = surface.animate( [{ opacity: 1 }, { opacity: SESSION_HANDOFF_OPACITY }], { duration: SESSION_HANDOFF_EXIT_DURATION_MS, easing: "cubic-bezier(0.2, 0, 0, 1)", fill: "forwards", }, ); }, [conversationKey, hasMessages, resetHistoryHeader]); useLayoutEffect(() => { if (!conversationReady) { threadMotionRef.current?.reset(); return; } if (!activeTurnId) { threadMotionRef.current?.completeTurn(); return; } const promptIndex = messages.findIndex( (message) => message.role === "user" && message.turnId === activeTurnId, ); if ( activeTurnStartedHere && promptIndex >= 0 && threadMotionRef.current?.snapshot().turnId !== activeTurnId ) { // A turn submitted in this mounted viewport establishes a new prompt // origin. A restored turn must first complete open-at-bottom instead. pendingConversationScrollRef.current = false; } const prompt = promptIndex >= 0 ? messages[promptIndex] : null; const hasOutput = promptIndex >= 0 ? messages .slice(promptIndex + 1) .some( (message) => message.role !== "user" && (!message.turnId || message.turnId === activeTurnId), ) : !activeTurnStartedHere && messages.some( (message) => message.role !== "user" && message.turnId === activeTurnId, ); threadMotionRef.current?.updateTurn({ id: activeTurnId, promptId: prompt?.id ?? null, hasOutput, entry: activeTurnStartedHere ? "submitted" : "restored", }); }, [activeTurnId, activeTurnStartedHere, conversationReady, messages]); useLayoutEffect(() => { const wasLoading = previousLoadingOlderRef.current; previousLoadingOlderRef.current = loadingOlder; if (!wasLoading || loadingOlder || olderError || !historySlotKey) return; // The completed render already removed the slot. Rebase the saved anchor // by its live presentation travel before the single final-geometry read. const anchor = historyScrollAnchorRef.current; if (anchor) anchor.offsetTop += historyDistanceRef.current; setShowHistoryExhausted(historyExhausted); resetHistoryHeader(); }, [loadingOlder, olderError, historySlotKey, historyExhausted, resetHistoryHeader]); useLayoutEffect(() => { const pending = restoreScrollAfterPrependRef.current; const el = scrollRef.current; restoreScrollAfterPrependRef.current = null; if (!el) return; if (reconcileHistoryScrollAnchor()) return; if (!pending) return; const delta = el.scrollHeight - pending.height; const nextTop = Math.min( Math.max(0, el.scrollHeight - el.clientHeight), Math.max(0, pending.top + delta), ); threadMotionRef.current?.jumpTo(nextTop); }, [reconcileHistoryScrollAnchor, visibleMessages.length, messages, loadingOlder]); useLayoutEffect(() => { const promptId = pendingPromptJumpRef.current; const scrollEl = scrollRef.current; if (!promptId || !scrollEl || !findPromptElement(scrollEl, promptId)) return; const frame = window.requestAnimationFrame(() => { if (pendingPromptJumpRef.current === promptId && navigateToVisiblePrompt(promptId)) { pendingPromptJumpRef.current = null; } }); return () => window.cancelAnimationFrame(frame); }, [navigateToVisiblePrompt, visibleMessages, navigation?.target]); useLayoutEffect(() => { if (!pendingConversationScrollRef.current) return; if (!conversationReady) return; if (!conversationKey) { pendingConversationScrollRef.current = false; scrollToBottom(false, { force: true }); return; } scrollToBottom(false, { force: true }); if (!hasMessages) return; pendingConversationScrollRef.current = false; }, [ conversationKey, conversationReady, hasMessages, messages, scrollToBottom, ]); useLayoutEffect(() => { // A request commits temporary space; successful completion reclaims it below. if (conversationReady && loadingOlder && scrollRef.current?.scrollTop === 0 && !historySlotRef.current) { holdHistoryHeader(); } }, [conversationReady, loadingOlder, holdHistoryHeader]); useLayoutEffect(() => { if (!conversationReady || !conversationHandoffPendingRef.current) return; conversationHandoffPendingRef.current = false; conversationHandoffAnimationRef.current?.cancel(); conversationHandoffAnimationRef.current = null; const surface = hasMessages ? messageRegionRef.current : emptyStateRef.current; const reduceMotion = typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches; if (!surface || reduceMotion || typeof surface.animate !== "function") return; const animation = surface.animate( [{ opacity: SESSION_HANDOFF_OPACITY }, { opacity: 1 }], { duration: SESSION_HANDOFF_ENTER_DURATION_MS, easing: "cubic-bezier(0.2, 0, 0, 1)", }, ); conversationHandoffAnimationRef.current = animation; const clearAnimation = () => { if (conversationHandoffAnimationRef.current === animation) { conversationHandoffAnimationRef.current = null; } }; animation.onfinish = clearAnimation; animation.oncancel = clearAnimation; }, [conversationReady, hasMessages]); useLayoutEffect(() => { threadMotionRef.current?.invalidateGeometry(); }, [composer, hasMessages, visibleMessages.length]); useEffect(() => () => { conversationHandoffAnimationRef.current?.cancel(); historySpringRef.current?.reset(); threadMotionRef.current?.dispose(); }, []); useLayoutEffect(() => { const el = scrollRef.current; const content = contentRef.current; const messageRegion = messageRegionRef.current; const messageContent = messageContentRef.current; const composerDock = composerDockRef.current; if (!el) return; const invalidateGeometry = () => { threadMotionRef.current?.invalidateGeometry(); }; const reconcileObservedGeometry = () => { reconcileHistoryScrollAnchor(); threadMotionRef.current?.reconcileObservedGeometry(); }; reconcileObservedGeometry(); const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(reconcileObservedGeometry); observer?.observe(el); if (content) observer?.observe(content); if (messageRegion) observer?.observe(messageRegion); if (messageContent) observer?.observe(messageContent); if (composerDock) observer?.observe(composerDock); window.addEventListener("resize", invalidateGeometry); return () => { observer?.disconnect(); window.removeEventListener("resize", invalidateGeometry); }; }, [hasMessages, reconcileHistoryScrollAnchor]); useEffect(() => { const el = scrollRef.current; if (!el) return; const onScroll = (allowHistoryLoad = true) => { setAtHistoryTop(el.scrollTop <= 1); if (el.scrollTop > 1) historySpringRef.current?.leaveBoundary(); const distance = el.scrollHeight - el.scrollTop - el.clientHeight; const near = distance < NEAR_BOTTOM_PX; // A detached history page's bottom is not the live tail. const owner = threadMotionRef.current?.observeScroll(near && !historyWindow) ?? "automatic"; const logicallyAtBottom = !historyWindow && (owner === "automatic" || (owner === "navigation" && near)); setAtBottom((current) => current === logicallyAtBottom ? current : logicallyAtBottom, ); if (owner === "user") { // Restoring the anchor also emits scroll. Keep that reading position // through lazy content resizing instead of selecting a prepended row. const anchor = historyScrollAnchorRef.current; if (!anchor || el.scrollTop !== anchor.scrollTop) captureHistoryScrollAnchor(); if (allowHistoryLoad) maybeLoadEarlierFromScroll(); if (allowHistoryLoad && distance < HISTORY_PREFETCH_MIN_PX && historyWindow?.hasMoreAfter && !navigation?.loading && !navigation?.error) navigation?.newer(); } else if (near) { historyScrollAnchorRef.current = null; } }; onScroll(false); const handleScroll = () => onScroll(true); const atHistoryBoundary = () => el.scrollTop <= 1 && messages.length > 0 && conversationReady && !pendingConversationScrollRef.current; const canLoadAtTop = () => atHistoryBoundary() && !loadingOlder && !navigation?.loading && (hiddenMessageCount > 0 || hasMoreBefore); const handleDirectionalInput = ( direction: ThreadScrollDirection | null, ) => { if (!direction) return; if (direction === "forward" && historyWindow?.hasMoreAfter && el.scrollHeight - el.scrollTop - el.clientHeight < HISTORY_PREFETCH_MIN_PX && !navigation?.loading) { captureHistoryScrollAnchor(); navigation?.newer(); } // At the top (including a page too short to scroll), backward intent // produces no scroll event. It must still be able to reveal history. if (direction === "backward" && canLoadAtTop()) { loadEarlierMessages(); return; } threadMotionRef.current?.handleUserScrollIntent( canScrollInDirection(el, direction), direction === "forward" && !historyWindow, ); }; const prepareHistoryPull = () => { if (loadingOlder || navigation?.loading) return; const first = messageContentRef.current?.querySelector(THREAD_DISPLAY_UNIT_SELECTOR); // A retained header belongs to the page boundary where it was opened, // not to a newer boundary reached by scrolling through prepended history. if (historySlotKey && first?.dataset.threadDisplayUnit !== historySlotKey) resetHistoryHeader(); }; const handleWheel = (event: WheelEvent) => { if ( event.defaultPrevented || event.ctrlKey || Math.abs(event.deltaY) <= Math.abs(event.deltaX) ) { return; } historyInputRef.current = "other"; if (atHistoryBoundary()) { const unit = event.deltaMode === WheelEvent.DOM_DELTA_LINE ? 16 : event.deltaMode === WheelEvent.DOM_DELTA_PAGE ? el.clientHeight : 1; if (event.deltaY < 0) { prepareHistoryPull(); yieldCameraToUser(); setAtHistoryTop(true); const first = historySpringRef.current?.wheel(-event.deltaY * unit); if ((first || olderError) && canLoadAtTop()) loadEarlierMessages(); return; } } handleDirectionalInput(directionFromDelta(event.deltaY)); }; const handlePointerDown = (event: PointerEvent) => { if ( event.button === 0 && (event.target === el || isThreadDisclosureTarget(event.target)) ) { yieldCameraToUser(); } }; const handleTouchCancel = () => { historyTouchRef.current = null; historySpringRef.current?.endTouch(true); }; const handleTouchStart = (event: TouchEvent) => { historyInputRef.current = "touch"; const touch = event.touches[0]; historyTouchRef.current = event.touches.length === 1 && touch ? { lastY: touch.clientY, startX: touch.clientX, startY: touch.clientY, pulling: false, horizontal: false, } : null; }; const handleTouchMove = (event: TouchEvent) => { const gesture = historyTouchRef.current; const touch = event.touches[0]; if (event.touches.length !== 1) { handleTouchCancel(); return; } if (!gesture || !touch || event.defaultPrevented) return; const delta = gesture.lastY - touch.clientY; gesture.lastY = touch.clientY; const horizontalTravel = Math.abs(touch.clientX - gesture.startX); const verticalTravel = Math.abs(touch.clientY - gesture.startY); if (!gesture.pulling && horizontalTravel > verticalTravel) gesture.horizontal = true; if (gesture.horizontal) return; if (gesture.pulling || (atHistoryBoundary() && delta < 0 && hiddenMessageCount === 0)) { if (!gesture.pulling) { prepareHistoryPull(); historySpringRef.current?.startTouch(); gesture.pulling = true; } if (event.cancelable) event.preventDefault(); yieldCameraToUser(); historySpringRef.current?.moveTouch(-delta); setAtHistoryTop(true); return; } handleDirectionalInput(directionFromDelta(delta)); }; const handleTouchEnd = () => { const pulling = historyTouchRef.current?.pulling; historyTouchRef.current = null; if (historySpringRef.current?.endTouch() && pulling && canLoadAtTop()) loadEarlierMessages(); }; const handleKeyDown = (event: KeyboardEvent) => { if ( event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || isKeyboardEditableElement(event.target as Element | null) ) { return; } if ( (event.key === "Enter" || event.key === " ") && isThreadDisclosureTarget(event.target) ) { yieldCameraToUser(); return; } if (isKeyboardControl(event.target as Element | null)) return; historyInputRef.current = "other"; handleDirectionalInput(keyboardScrollDirection(event)); }; el.addEventListener("scroll", handleScroll, { passive: true }); el.addEventListener("wheel", handleWheel, { passive: true }); el.addEventListener("touchstart", handleTouchStart, { passive: true }); el.addEventListener("touchmove", handleTouchMove, { passive: false }); el.addEventListener("touchend", handleTouchEnd, { passive: true }); el.addEventListener("touchcancel", handleTouchCancel, { passive: true }); el.addEventListener("pointerdown", handlePointerDown); el.addEventListener("keydown", handleKeyDown); return () => { el.removeEventListener("scroll", handleScroll); el.removeEventListener("wheel", handleWheel); el.removeEventListener("touchstart", handleTouchStart); el.removeEventListener("touchmove", handleTouchMove); el.removeEventListener("touchend", handleTouchEnd); el.removeEventListener("touchcancel", handleTouchCancel); el.removeEventListener("pointerdown", handlePointerDown); el.removeEventListener("keydown", handleKeyDown); }; }, [ captureHistoryScrollAnchor, conversationReady, hasMessages, hasMoreBefore, hiddenMessageCount, loadingOlder, loadEarlierMessages, maybeLoadEarlierFromScroll, messages.length, olderError, yieldCameraToUser, historySlotKey, historyWindow, navigation, resetHistoryHeader, ]); const navigationStatus = navigation?.operation !== "older" && Boolean(navigation?.loading || navigation?.error); const showHistoryStatus = !historySlotCompleted && !navigationStatus && messages.length > 0 && conversationReady && (atHistoryTop && (!historyExhausted || showHistoryExhausted) || historyPhase !== "hidden" || loadingOlder); const historyStatus = showHistoryStatus ? ( ) : null; return (
{hasMessages ? (
{historyStatus}
) } : undefined} temporary={temporary} isStreaming={isStreaming} activeTurnId={activeTurnId} runStartedAt={runStartedAt} retryStatus={retryStatus} hiddenUserMessageCount={hiddenUserMessageCount} cliApps={cliApps} mcpPresets={mcpPresets} slashCommands={slashCommands} forkBoundaryMessageCount={visibleForkBoundaryMessageCount} traceDetailScope={traceDetailScope} onLoadTraceDetails={onLoadTraceDetails} onOpenFilePreview={onOpenFilePreview} onForkFromMessage={onForkFromMessage} onQuoteSelection={onQuoteSelection} onActivityToggle={yieldCameraToUser} />
) : (
{emptyState}
)} {hasComposer ? (
{ if (event.target instanceof HTMLTextAreaElement) { threadMotionRef.current?.handleComposerInput(); } }} className={cn( "row-start-2 z-10 w-full", hasThreadLayout ? "thread-composer-dock relative" : "relative self-center", )} >
{composer}
) : null} {hasComposer ? (
) : null}
{!retainedHistorySlotKey ? historyStatus : null} {navigationStatus && navigation ? : null} {!hasMessages ?
: null}
{hasMessages ? ( ) : null} {showScrollToBottomButton && (!atBottom || historyWindow) && (
)}
); });