Files
paseo/packages/app/src/agent-stream/strategy-web.tsx
T
Mohamed Boudra 02ad59908f Keep show more and plan card toggles in place on Android (#9085)
* fix(app): keep show more and plan card triggers in place on expand

Long user message previews and plan cards toggled with a plain setState,
skipping the timeline's disclosure hold. On Android the expanded content
painted over the next row for a frame before the list learned the new
size and corrected the scroll. Route both toggles through
useDisclosureHold like the other timeline disclosures.

* fix(app): keep show more at the same y by holding the message's bottom edge

Show more sits under the text it opens, so a top-anchored hold pushed it off
screen. The disclosure hold takes a trigger edge; MessagePreview passes the
bottom edge. Web pins that edge in the reading anchor, native anchors the row
below the message, and while following the end pin keeps the bottom in place.
The LegendList patch counts the row just past the viewport as in view and drops
the Android clamp prediction that moved a collapse near the end to the end.

* fix(app): keep show more in place on an unanswered final prompt

The last row has no row below it to anchor its bottom on, so a show more
on a prompt the agent has not answered yet moved the trigger off screen.
The hold now mounts the end pin while detached and toggles a frame later,
once the pin anchors, and re-sticks only if the list was at its end when
the toggle was tapped.

The disclosure browser test now renders the real Markdown renderer.

* fix(app): resume following when a final prompt collapse reaches the end

An end hold decided its release from whether the list was at its end
when tapped. A collapse that leaves less scroll room than that distance
ends at the end, so the list stayed detached and later output grew below
the viewport. The release now clamps the tapped distance to the room
left. A row hold also clears an end hold still in progress, so the plan
card or another toggle anchors its own row.

* fix(app): keep following when a reply lands during a final prompt collapse

The end hold clamped its distance from the end only against the final
content size. A reply that grew the content after a collapse reached the
end brought the old distance back, so the hold released detached. The
hold now clamps on every content size change.

* fix(app): let a reply grow below a held final prompt

An end hold pinned the content end for the whole hold, so a reply that
landed during it scrolled the toggled prompt up. The pin now holds only
while the toggled row is the last row, and drops in the commit that
mounts the reply.

* fix(app): move a waiting final prompt hold to a reply that lands first

The end hold's toggle waits a frame for the end pin, and it kept the
anchor from the tap. A reply landing in that frame dropped the pin but
left the hold with no row, so the toggle moved the button. The disclosure
hold now owns the waiting toggle and resolves the anchor when the frame
runs.
2026-11-08 15:34:26 +07:00

1420 lines
50 KiB
TypeScript

import React, {
type CSSProperties,
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import {
defaultRangeExtractor,
observeElementOffset,
measureElement as measureVirtualElement,
useVirtualizer,
type Range as VirtualRange,
type Virtualizer,
} from "@tanstack/react-virtual";
import { flushSync } from "react-dom";
import { withUnistyles } from "react-native-unistyles";
import { useRetainedPanelActive } from "@/components/retained-panel";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { useStableEvent } from "@/hooks/use-stable-event";
import { useTranslation } from "react-i18next";
import { getStreamItemMessageId, type StreamItem } from "@/types/stream";
import type { Theme } from "@/styles/theme";
import { WEB_SCROLLBAR_SIZE_PX } from "@/styles/web-scrollbar";
import { DomOverlayScrollbar } from "@/components/ui/overlay-scrollbar/dom-overlay-scrollbar";
import { estimateStreamItemHeight } from "./web-virtualization";
import { createReadingAnchor } from "./reading-anchor";
import type { StreamRenderInput, StreamStrategy, StreamViewportHandle } from "./strategy";
import { useRevisedHistoryRows } from "./history-row-revision";
import { createStreamStrategy } from "./strategy";
import {
isHistoryStartLoadingOperation,
type HistoryStartPaginationInput,
} from "./history-start-pagination";
import { useHistoryStartPagination } from "./use-history-start-pagination";
import {
createHistoryStartSettleScheduler,
type HistoryStartSettleScheduler,
} from "./history-start-settle-scheduler";
import { useChatFindSelectedMessageId } from "@/agent-stream/chat-find";
import { useScrollToMessage } from "./use-scroll-to-message.web";
interface CreateWebStreamStrategyInput {
isMobileBreakpoint: boolean;
}
type ScrollBehaviorLike = "auto" | "smooth";
const WEB_BOTTOM_SETTLE_TIMEOUT_MS = 200;
const USER_SCROLL_DELTA_EPSILON = 1;
const BOTTOM_OVERSCROLL_TOLERANCE_PX = 2;
const AUTO_SCROLL_BOTTOM_THRESHOLD_PX = 64;
const AUTO_SCROLL_RESUME_THRESHOLD_PX = 1;
const HISTORY_START_SETTLE_FRAMES = 2;
const HISTORY_START_SLOT_HEIGHT_PX = 32;
const CONTENT_PADDING_TOP_PX = 16;
const UPWARD_INPUT_EVIDENCE_TIMEOUT_MS = 100;
const VIRTUALIZER_SCROLL_MARGIN_PX = HISTORY_START_SLOT_HEIGHT_PX + CONTENT_PADDING_TOP_PX;
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const foregroundMutedColorMapping = (theme: Theme) => ({
color: theme.colors.foregroundMuted,
});
const historyStartSlotStyle: CSSProperties = {
display: "flex",
alignItems: "center",
justifyContent: "center",
height: HISTORY_START_SLOT_HEIGHT_PX,
flexShrink: 0,
};
const streamRowsHostStyle: CSSProperties = { position: "relative", width: "100%" };
const initialFillStyle: CSSProperties = {
position: "absolute",
inset: 0,
display: "flex",
alignItems: "center",
justifyContent: "center",
pointerEvents: "none",
};
// Rows and the live auxiliary (turn footer, pending permissions) center their content with
// `alignSelf`, which only applies inside a flex container.
const streamRowStyle: CSSProperties = {
display: "flex",
flexDirection: "column",
width: "100%",
};
function isScrollContainerNearBottom(
scrollContainer: Pick<HTMLElement, "scrollTop" | "clientHeight" | "scrollHeight">,
thresholdPx = AUTO_SCROLL_BOTTOM_THRESHOLD_PX,
): boolean {
const threshold = Number.isFinite(thresholdPx)
? Math.max(0, thresholdPx)
: AUTO_SCROLL_BOTTOM_THRESHOLD_PX;
const { scrollTop, clientHeight, scrollHeight } = scrollContainer;
if (![scrollTop, clientHeight, scrollHeight].every(Number.isFinite)) {
return true;
}
const distanceFromBottom = scrollHeight - clientHeight - scrollTop;
return distanceFromBottom <= threshold;
}
function isScrollContainerAtBottom(
scrollContainer: Pick<HTMLElement, "scrollTop" | "clientHeight" | "scrollHeight">,
): boolean {
return isScrollContainerNearBottom(scrollContainer, AUTO_SCROLL_RESUME_THRESHOLD_PX);
}
function isScrollContainerMeasurable(
scrollContainer: Pick<HTMLElement, "clientHeight" | "scrollHeight">,
): boolean {
return scrollContainer.clientHeight > 0 && scrollContainer.scrollHeight > 0;
}
function isEditableEventTarget(target: EventTarget | null): boolean {
if (!(target instanceof Element)) {
return false;
}
const editableRoot = target.closest("input, textarea, [contenteditable]");
if (!editableRoot) {
return false;
}
const tagName = editableRoot.tagName.toLowerCase();
if (tagName === "input" || tagName === "textarea") {
return true;
}
return editableRoot.getAttribute("contenteditable")?.toLowerCase() !== "false";
}
function isUpwardViewportScrollKey(event: KeyboardEvent): boolean {
if (isEditableEventTarget(event.target)) {
return false;
}
return (
event.key === "ArrowUp" ||
event.key === "PageUp" ||
event.key === "Home" ||
(event.key === " " && event.shiftKey)
);
}
function canNestedScrollerConsumeUpwardInput(
target: EventTarget | null,
scrollContainer: HTMLElement,
): boolean {
let element = target instanceof Element ? target : null;
while (element && element !== scrollContainer) {
if (element instanceof HTMLElement) {
const overflowY = window.getComputedStyle(element).overflowY;
const canScroll = overflowY === "auto" || overflowY === "scroll";
if (canScroll && element.scrollHeight > element.clientHeight && element.scrollTop > 0) {
return true;
}
}
element = element.parentElement;
}
return false;
}
function isVerticalScrollbarGutterPress(
event: PointerEvent,
scrollContainer: HTMLElement,
): boolean {
if (event.target !== scrollContainer) {
return false;
}
if (scrollContainer.scrollHeight <= scrollContainer.clientHeight) {
return false;
}
const scrollbarWidth = Math.max(
scrollContainer.offsetWidth - scrollContainer.clientWidth,
WEB_SCROLLBAR_SIZE_PX,
);
const bounds = scrollContainer.getBoundingClientRect();
return window.getComputedStyle(scrollContainer).direction === "rtl"
? event.clientX <= bounds.left + scrollbarWidth
: event.clientX >= bounds.right - scrollbarWidth;
}
function scrollElementToBottom(
scrollContainer: HTMLElement,
behavior: ScrollBehaviorLike = "auto",
): void {
scrollContainer.scrollTo({
top: scrollContainer.scrollHeight,
behavior,
});
}
function syncNearBottom(
scrollContainer: HTMLElement | null,
onNearBottomChange: (value: boolean) => void,
): boolean {
if (!scrollContainer) {
onNearBottomChange(true);
return true;
}
const nextValue = isScrollContainerNearBottom(scrollContainer);
onNearBottomChange(nextValue);
return nextValue;
}
interface ActiveFollowOutputLayout {
scrollContainer: HTMLElement | null;
viewportWidth: number;
viewportHeight: number;
activationKey: string;
isActivationReady: boolean;
renderLiveAuxiliary: StreamRenderInput["renderers"]["renderLiveAuxiliary"];
historyMounted: StreamRenderInput["segments"]["historyMounted"];
historyVirtualized: StreamRenderInput["segments"]["historyVirtualized"];
liveHead: StreamRenderInput["segments"]["liveHead"];
virtualTotalSize: number;
}
function activeFollowOutputLayoutsEqual(
previous: ActiveFollowOutputLayout,
next: ActiveFollowOutputLayout,
): boolean {
return (
previous.scrollContainer === next.scrollContainer &&
previous.viewportWidth === next.viewportWidth &&
previous.viewportHeight === next.viewportHeight &&
previous.activationKey === next.activationKey &&
previous.isActivationReady === next.isActivationReady &&
previous.renderLiveAuxiliary === next.renderLiveAuxiliary &&
previous.historyMounted === next.historyMounted &&
previous.historyVirtualized === next.historyVirtualized &&
previous.liveHead === next.liveHead &&
previous.virtualTotalSize === next.virtualTotalSize
);
}
interface ObservedViewportGeometry {
clientWidth: number;
clientHeight: number;
scrollWidth: number;
scrollHeight: number;
}
function getObservedViewportGeometry(scrollContainer: HTMLElement): ObservedViewportGeometry {
return {
clientWidth: scrollContainer.clientWidth,
clientHeight: scrollContainer.clientHeight,
scrollWidth: scrollContainer.scrollWidth,
scrollHeight: scrollContainer.scrollHeight,
};
}
function observedViewportGeometriesEqual(
previous: ObservedViewportGeometry,
next: ObservedViewportGeometry,
): boolean {
return (
previous.clientWidth === next.clientWidth &&
previous.clientHeight === next.clientHeight &&
previous.scrollWidth === next.scrollWidth &&
previous.scrollHeight === next.scrollHeight
);
}
function getScrollContainerDistanceFromBottom(
scrollContainer: Pick<HTMLElement, "scrollTop" | "clientHeight" | "scrollHeight">,
): number {
return scrollContainer.scrollHeight - scrollContainer.clientHeight - scrollContainer.scrollTop;
}
function isScrollContainerOverscrolledPastBottom(
scrollContainer: Pick<HTMLElement, "scrollTop" | "clientHeight" | "scrollHeight">,
): boolean {
return getScrollContainerDistanceFromBottom(scrollContainer) < -BOTTOM_OVERSCROLL_TOLERANCE_PX;
}
// Position updates do not change a row's content. Keep renderer work separate
// from virtual measurements while retaining the same component across lanes.
const StreamRowContent = React.memo(function StreamRowContent({
item,
index,
items,
render,
}: {
revision?: StreamRenderInput["liveHeadRowRevision"];
item: StreamItem;
index: number;
items: StreamItem[];
render: StreamRenderInput["renderers"]["renderHistoryVirtualizedRow"];
}) {
return render(item, index, items);
});
function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: boolean }) {
const {
segments: inputSegments,
historyRowRevision,
liveHeadRowRevision,
boundary,
renderers,
listEmptyComponent,
viewportRef,
routeBottomAnchorRequest,
isAuthoritativeHistoryReady,
isInitialHistoryLoading,
revealInitialHistory,
onNearBottomChange,
onReadingPositionChange,
onNearHistoryStart,
isLoadingOlderHistory,
hasOlderHistory,
olderHistoryProgressKey,
scrollEnabled,
contentMaxWidth,
isMobileBreakpoint,
} = props;
const historyVirtualized = useRevisedHistoryRows(
inputSegments.historyVirtualized,
historyRowRevision,
);
const historyMounted = useRevisedHistoryRows(inputSegments.historyMounted, historyRowRevision);
const segments = useMemo(
() => ({ ...inputSegments, historyVirtualized, historyMounted }),
[historyMounted, historyVirtualized, inputSegments],
);
const isActive = useRetainedPanelActive();
const { t } = useTranslation();
const rowsHostRef = useRef<HTMLDivElement | null>(null);
const auxiliaryRef = useRef<HTMLDivElement | null>(null);
const isActiveRef = useRef(isActive);
const scrollContainerRef = useRef<HTMLElement | null>(null);
const contentRef = useRef<HTMLElement | null>(null);
const handleScrollContainerRef = useCallback((node: HTMLElement | null) => {
scrollContainerRef.current = node;
}, []);
const handleContentRef = useCallback((node: HTMLElement | null) => {
contentRef.current = node;
}, []);
const [followOutput, setFollowOutputr] = useState(true);
const followOutputRef = useRef(followOutput);
const setFollowOutput = (value: boolean) => {
followOutputRef.current = value;
setFollowOutputr(value);
return value;
};
const lastKnownScrollTopRef = useRef(0);
const mouseScrollGestureRef = useRef<
| { kind: "scrollbar"; pointerId: number }
| {
kind: "autoscroll";
pointerId: number;
lastClientY: number;
hasUpwardEvidence: boolean;
evidenceExpiryFrame: number | null;
}
| null
>(null);
const upwardInputEvidenceUntilRef = useRef(0);
const lastTouchClientYRef = useRef<number | null>(null);
const pendingAutoScrollFrameRef = useRef<number | null>(null);
const pendingAutoScrollTimeoutRef = useRef<number | null>(null);
const historyStartReadyRef = useRef(false);
const readingAnchor = useMemo(createReadingAnchor, []);
const measuredRowHeights = useRef(new Map<string, { width: number; height: number }>());
const historyStartSettleSchedulerRef = useRef<HistoryStartSettleScheduler | null>(null);
const lastActiveFollowOutputLayoutRef = useRef<ActiveFollowOutputLayout | null>(null);
const lastObservedViewportGeometryRef = useRef<ObservedViewportGeometry | null>(null);
const wasFollowOutputLayoutActiveRef = useRef(false);
const resumedUnchangedLayoutRef = useRef(false);
const pendingResumeGeometryCheckRef = useRef(false);
// Set by holdRow; the next reading reconcile sees the disclosure's layout.
const disclosurePendingRef = useRef(false);
const shouldUseVirtualizer = segments.historyVirtualized.length > 0;
const {
renderHistoryVirtualizedRow,
renderHistoryMountedRow,
renderLiveHeadRow,
renderLiveAuxiliary,
} = renderers;
isActiveRef.current = isActive;
followOutputRef.current = followOutput;
const hasRouteBottomAnchorRequest = routeBottomAnchorRequest !== null;
const activationKey = routeBottomAnchorRequest?.requestKey ?? props.agentId;
const isActivationReady = !hasRouteBottomAnchorRequest || isAuthoritativeHistoryReady;
// Chat find counts and highlights occurrences from the DOM, so every block row of
// the message it selected has to be mounted even when the scroll window is nowhere
// near it. Without this a hit in a far paragraph is invisible to the count and Next
// walks off to the following message.
const chatFindMessageId = useChatFindSelectedMessageId();
const chatFindRowIndexes = useMemo(() => {
if (!chatFindMessageId) return null;
const indexes = segments.historyVirtualized.flatMap((item, index) =>
getStreamItemMessageId(item) === chatFindMessageId ? [index] : [],
);
return indexes.length > 0 ? indexes : null;
}, [chatFindMessageId, segments.historyVirtualized]);
const rowVirtualizerRef = useRef<Virtualizer<HTMLElement, Element> | null>(null);
const rangeExtractor = useCallback(
(range: VirtualRange): number[] => {
const anchorIndex = segments.historyVirtualized.findIndex(
(row) => row.id === readingAnchor.getRowId(props.readingRowReplacements),
);
const container = scrollContainerRef.current;
// TanStack has computed the new measurements before calling the extractor.
// Select against the pending anchor correction, before mounting any rows at
// the stale pre-prepend offset. The DOM correction still belongs to commit.
const virtualizer = rowVirtualizerRef.current!;
const measurement = virtualizer.measurementsCache[anchorIndex];
const correctedOffset =
container && measurement
? readingAnchor.project(
container.scrollTop,
{
id: String(measurement.key),
top: measurement.start,
height: measurement.size,
},
props.readingRowReplacements,
)
: container?.scrollTop;
let visibleRange = range;
if (
container &&
correctedOffset !== undefined &&
Math.abs(correctedOffset - container.scrollTop) > 0.5
) {
const first = virtualizer.getVirtualItemForOffset(correctedOffset);
const last = virtualizer.getVirtualItemForOffset(correctedOffset + container.clientHeight);
if (first && last)
visibleRange = { ...range, startIndex: first.index, endIndex: last.index };
}
return [
...new Set([
...defaultRangeExtractor(visibleRange),
...(chatFindRowIndexes ?? []),
...(anchorIndex < 0 ? [] : [anchorIndex]),
]),
].sort((left, right) => left - right);
},
[chatFindRowIndexes, readingAnchor, segments.historyVirtualized, props.readingRowReplacements],
);
const virtualOffsetListener = useRef<((offset: number, scrolling: boolean) => void) | null>(null);
const observeVirtualOffset = useCallback<typeof observeElementOffset>((instance, onOffset) => {
virtualOffsetListener.current = onOffset;
const unsubscribe = observeElementOffset(instance, onOffset);
return () => {
virtualOffsetListener.current = null;
unsubscribe?.();
};
}, []);
const contentWidth = contentRef.current?.getBoundingClientRect().width;
const rowVirtualizer = useVirtualizer({
count: segments.historyVirtualized.length,
enabled: shouldUseVirtualizer,
initialRect: {
width: scrollContainerRef.current?.clientWidth ?? 0,
height: scrollContainerRef.current?.clientHeight ?? 0,
},
getScrollElement: () => scrollContainerRef.current,
getItemKey: (index: number) => segments.historyVirtualized[index]?.id ?? index,
estimateSize: (index: number) => {
const row = segments.historyVirtualized[index];
const measured = row && measuredRowHeights.current.get(row.id);
if (measured && measured.width === contentWidth) return measured.height;
return row ? estimateStreamItemHeight({ item: row, contentMaxWidth }) : 120;
},
observeElementOffset: observeVirtualOffset,
rangeExtractor,
scrollMargin: VIRTUALIZER_SCROLL_MARGIN_PX,
overscan: 8,
});
rowVirtualizerRef.current = rowVirtualizer;
// Scroll correction belongs to the viewport's committed layout. The virtualizer
// otherwise writes scrollTop before React applies its new row positions.
rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = () => false;
const virtualRows = rowVirtualizer.getVirtualItems();
const virtualTotalSize = rowVirtualizer.getTotalSize();
const getHistoryStartPaginationInput = useStableEvent((): HistoryStartPaginationInput | null => {
const scrollContainer = scrollContainerRef.current;
if (!isActiveRef.current || !scrollContainer || !isScrollContainerMeasurable(scrollContainer)) {
return null;
}
const bottomAnchorSettled =
!followOutputRef.current || isScrollContainerNearBottom(scrollContainer);
return {
distanceFromHistoryStart: scrollContainer.scrollTop,
isUnderfilled:
(rowsHostRef.current?.getBoundingClientRect().height ?? 0) +
(auxiliaryRef.current?.getBoundingClientRect().height ?? 0) <
scrollContainer.clientHeight,
hasOlderHistory,
isLoadingOlderHistory,
// An explicit jump owns the landing position. Revealing another local
// page here changes the virtual index before the target has mounted.
isReady:
historyStartReadyRef.current &&
isAuthoritativeHistoryReady &&
bottomAnchorSettled &&
!isJumpSettling(),
progressKey: olderHistoryProgressKey,
};
});
const { state: historyStartPaginationState, controller: historyStartPagination } =
useHistoryStartPagination({
initiallyVisible: !isInitialHistoryLoading,
read: getHistoryStartPaginationInput,
load: async () => onNearHistoryStart(),
scheduleSettle: () => scheduleHistoryStartPrependSettle(),
});
const evaluateHistoryStart = useStableEvent(() => historyStartPagination.update());
const disposeHistoryStart = useStableEvent(() => historyStartPagination.dispose());
const isHistoryStartSettling = useStableEvent(
() => historyStartPagination.state.status === "settling",
);
const finishInitialFill = useStableEvent(() => historyStartPagination.reveal());
const rearmHistoryStartFromUserIntent = useStableEvent(() => historyStartPagination.rearm());
const scheduleHistoryStartPrependSettle = useStableEvent(() => {
let scheduler = historyStartSettleSchedulerRef.current;
if (!scheduler) {
scheduler = createHistoryStartSettleScheduler({
settleFrames: HISTORY_START_SETTLE_FRAMES,
requestFrame: (callback) => window.requestAnimationFrame(callback),
cancelFrame: (frame) => window.cancelAnimationFrame(frame),
isSettling: () => isHistoryStartSettling(),
isLoading: () => {
const input = getHistoryStartPaginationInput();
return !input || input.isLoadingOlderHistory;
},
onSettle: () => historyStartPagination.settle(),
});
historyStartSettleSchedulerRef.current = scheduler;
}
scheduler.schedule();
});
const measureVirtualizedRows = useStableEvent(() => {
let resized = false;
for (const element of contentRef.current?.querySelectorAll<HTMLElement>(
"[data-history-row-id][data-index]",
) ?? []) {
const index = Number(element.dataset.index);
const height = measureVirtualElement(element, undefined, rowVirtualizer);
if (rowVirtualizer.measurementsCache[index]?.size === height) continue;
rowVirtualizer.resizeItem(index, height);
resized = true;
}
return resized;
});
// Measure the committed DOM rather than queued observer entries: flushSync can
// also commit an image's pending intrinsic dimensions, invalidating those entries.
const virtualRowObserver = useMemo(
() =>
new ResizeObserver(() => {
if (!isActiveRef.current) return;
flushSync(() => {
measureVirtualizedRows();
});
}),
[measureVirtualizedRows],
);
const measureVirtualizedRowElement = useCallback(
(node: HTMLDivElement | null) => {
if (!node) return;
virtualRowObserver.observe(node, { box: "border-box" });
return () => virtualRowObserver.unobserve(node);
},
[virtualRowObserver],
);
useEffect(() => () => virtualRowObserver.disconnect(), [virtualRowObserver]);
const cancelPendingStickToBottom = useCallback(() => {
const pendingFrame = pendingAutoScrollFrameRef.current;
if (pendingFrame !== null) {
pendingAutoScrollFrameRef.current = null;
window.cancelAnimationFrame(pendingFrame);
}
const pendingTimeout = pendingAutoScrollTimeoutRef.current;
if (pendingTimeout !== null) {
pendingAutoScrollTimeoutRef.current = null;
window.clearTimeout(pendingTimeout);
}
}, []);
const clearMouseScrollGesture = useCallback(() => {
const gesture = mouseScrollGestureRef.current;
const evidenceExpiryFrame = gesture?.kind === "autoscroll" ? gesture.evidenceExpiryFrame : null;
if (evidenceExpiryFrame !== null && evidenceExpiryFrame !== undefined) {
window.cancelAnimationFrame(evidenceExpiryFrame);
}
mouseScrollGestureRef.current = null;
}, []);
const clearUpwardInputEvidence = useCallback(() => {
upwardInputEvidenceUntilRef.current = 0;
}, []);
const markUpwardInputEvidence = useCallback(() => {
upwardInputEvidenceUntilRef.current =
window.performance.now() + UPWARD_INPUT_EVIDENCE_TIMEOUT_MS;
}, []);
useLayoutEffect(() => {
if (isActive) {
return;
}
cancelPendingStickToBottom();
historyStartSettleSchedulerRef.current?.cancel();
clearMouseScrollGesture();
clearUpwardInputEvidence();
lastTouchClientYRef.current = null;
}, [cancelPendingStickToBottom, clearMouseScrollGesture, clearUpwardInputEvidence, isActive]);
const scrollMessagesToBottom = useCallback(
(behavior: ScrollBehaviorLike = "auto") => {
const scrollContainer = scrollContainerRef.current;
if (
!isActiveRef.current ||
!scrollContainer ||
!isScrollContainerMeasurable(scrollContainer)
) {
return;
}
if (isScrollContainerOverscrolledPastBottom(scrollContainer)) {
return;
}
scrollElementToBottom(scrollContainer, behavior);
lastKnownScrollTopRef.current = scrollContainer.scrollTop;
syncNearBottom(scrollContainer, onNearBottomChange);
evaluateHistoryStart();
},
[evaluateHistoryStart, onNearBottomChange],
);
const scheduleStickToBottom = useCallback(() => {
if (!isActiveRef.current) {
return;
}
const scrollContainer = scrollContainerRef.current;
if (scrollContainer && isScrollContainerOverscrolledPastBottom(scrollContainer)) {
return;
}
if (pendingAutoScrollFrameRef.current !== null) {
return;
}
pendingAutoScrollFrameRef.current = window.requestAnimationFrame(() => {
pendingAutoScrollFrameRef.current = null;
if (!isActiveRef.current || !followOutputRef.current) {
return;
}
scrollMessagesToBottom("auto");
});
}, [scrollMessagesToBottom]);
const forceStickToBottom = useCallback(() => {
cancelPendingStickToBottom();
scrollMessagesToBottom("auto");
scheduleStickToBottom();
}, [cancelPendingStickToBottom, scheduleStickToBottom, scrollMessagesToBottom]);
// Rows are laid out in DOM order, virtualized block first, so the first row whose bottom
// clears the reading line is the one the reader is looking at.
const reportReadingPosition = useStableEvent(() => {
if (!isActiveRef.current) {
return;
}
if (!onReadingPositionChange) {
return;
}
const scrollContainer = scrollContainerRef.current;
const contentNode = contentRef.current;
if (!scrollContainer || !contentNode) {
onReadingPositionChange(null);
return;
}
onReadingPositionChange(readingAnchor.getReadingRowId(scrollContainer.scrollTop));
});
const updateScrollMetrics = useCallback(() => {
if (!isActiveRef.current) {
return;
}
const scrollContainer = scrollContainerRef.current;
if (!scrollContainer) {
onNearBottomChange(true);
return;
}
syncNearBottom(scrollContainer, onNearBottomChange);
reportReadingPosition();
}, [onNearBottomChange, reportReadingPosition]);
const { isJumpSettling, scrollToMessage } = useScrollToMessage({
active: isActive,
scrollContainerRef,
rowVirtualizer,
historyVirtualized: segments.historyVirtualized,
cancelPendingStickToBottom,
setFollowOutput,
onNearBottomChange,
});
// Row tops in content coordinates, which survive scrolling.
const measureRows = useStableEvent(() => {
const container = scrollContainerRef.current;
const content = contentRef.current;
if (!container || !content) return null;
const viewportTop = container.getBoundingClientRect().top;
const scrollTop = container.scrollTop;
const width = content.getBoundingClientRect().width;
return Array.from(content.querySelectorAll<HTMLElement>("[data-history-row-id]"), (element) => {
const bounds = element.getBoundingClientRect();
const id = element.dataset.historyRowId!;
measuredRowHeights.current.set(id, { width, height: bounds.height });
return { id, top: bounds.top - viewportTop + scrollTop, height: bounds.height };
});
});
const reconcileReadingPosition = useStableEvent(() => {
const container = scrollContainerRef.current;
if (!isActiveRef.current || !container) return;
const rows = measureRows();
if (!rows) return;
const shouldAnchor = !followOutputRef.current && !isJumpSettling();
if (!shouldAnchor) readingAnchor.reset();
const correctedTop = readingAnchor.reconcile(
container.scrollTop,
rows,
false,
props.readingRowReplacements,
);
if (!shouldAnchor) {
readingAnchor.reset();
return;
}
if (Math.abs(correctedTop - container.scrollTop) > 0.5) {
container.scrollTop = correctedTop;
lastKnownScrollTopRef.current = container.scrollTop;
// The DOM scroll event arrives later. Fill the corrected virtual range in
// this layout so the reader does not get a frame containing only the pin.
virtualOffsetListener.current?.(container.scrollTop, false);
}
// A disclosure that closes back to the end of the list rejoins the output.
if (disclosurePendingRef.current) {
disclosurePendingRef.current = false;
if (isScrollContainerAtBottom(container)) setFollowOutput(true);
}
});
// Apply row positions and their scroll correction in the same paint, including
// the ordinary-to-virtualized handoff and measurements of newly mounted rows.
useLayoutEffect(() => {
// Commit positions for every resized row before accepting reading geometry.
// Child layout can change during this commit, ahead of ResizeObserver delivery.
if (!isActive || measureVirtualizedRows()) return;
reconcileReadingPosition();
}, [
contentWidth,
isActive,
segments,
virtualRows,
measureVirtualizedRows,
reconcileReadingPosition,
]);
const stopFollowingOutputFromUserIntent = useStableEvent(() => {
finishInitialFill();
cancelPendingStickToBottom();
if (followOutputRef.current) {
setFollowOutput(false);
}
rearmHistoryStartFromUserIntent();
});
useEffect(() => {
if (revealInitialHistory) finishInitialFill();
}, [finishInitialFill, revealInitialHistory]);
const handleDomScroll = useCallback(() => {
const scrollContainer = scrollContainerRef.current;
if (!isActiveRef.current || !scrollContainer || !isScrollContainerMeasurable(scrollContainer)) {
return;
}
const currentScrollTop = scrollContainer.scrollTop;
const isAtBottom = isScrollContainerAtBottom(scrollContainer);
const scrolledUp = currentScrollTop < lastKnownScrollTopRef.current - USER_SCROLL_DELTA_EPSILON;
const scrolledDown =
currentScrollTop > lastKnownScrollTopRef.current + USER_SCROLL_DELTA_EPSILON;
const mouseGesture = mouseScrollGestureRef.current;
const hasUpwardInputEvidence =
mouseGesture?.kind === "scrollbar" ||
(mouseGesture?.kind === "autoscroll" && mouseGesture.hasUpwardEvidence) ||
window.performance.now() < upwardInputEvidenceUntilRef.current;
if (!followOutputRef.current && isAtBottom && scrolledDown && !isJumpSettling()) {
setFollowOutput(true);
} else if (followOutputRef.current && scrolledUp && hasUpwardInputEvidence) {
stopFollowingOutputFromUserIntent();
}
lastKnownScrollTopRef.current = currentScrollTop;
if (!followOutputRef.current && !isJumpSettling() && (scrolledUp || scrolledDown)) {
readingAnchor.scroll(currentScrollTop);
}
updateScrollMetrics();
evaluateHistoryStart();
}, [
evaluateHistoryStart,
isJumpSettling,
readingAnchor,
stopFollowingOutputFromUserIntent,
updateScrollMetrics,
]);
useEffect(() => {
const frame = window.requestAnimationFrame(() => {
historyStartReadyRef.current = true;
evaluateHistoryStart();
});
return () => {
window.cancelAnimationFrame(frame);
historyStartReadyRef.current = false;
disposeHistoryStart();
historyStartSettleSchedulerRef.current?.cancel();
historyStartSettleSchedulerRef.current = null;
};
}, [disposeHistoryStart, evaluateHistoryStart]);
useLayoutEffect(() => {
if (!isActiveRef.current || !isActivationReady) {
return;
}
if (hasRouteBottomAnchorRequest && !followOutputRef.current) {
return;
}
setFollowOutput(true);
forceStickToBottom();
const timeout = window.setTimeout(() => {
if (!followOutputRef.current) {
return;
}
const scrollContainer = scrollContainerRef.current;
if (!scrollContainer) {
return;
}
if (isScrollContainerNearBottom(scrollContainer)) {
return;
}
scheduleStickToBottom();
}, WEB_BOTTOM_SETTLE_TIMEOUT_MS);
return () => {
window.clearTimeout(timeout);
};
}, [
activationKey,
forceStickToBottom,
hasRouteBottomAnchorRequest,
isActivationReady,
scheduleStickToBottom,
]);
// Following output is a layout invariant: rows, footer, and bottom offset must
// reach the browser in the same paint.
useLayoutEffect(() => {
const layout: ActiveFollowOutputLayout = {
scrollContainer: scrollContainerRef.current,
viewportWidth: window.innerWidth,
viewportHeight: window.innerHeight,
activationKey,
isActivationReady,
renderLiveAuxiliary,
historyMounted: segments.historyMounted,
historyVirtualized: segments.historyVirtualized,
liveHead: segments.liveHead,
virtualTotalSize,
};
const resumedUnchangedLayout = Boolean(
isActive &&
!wasFollowOutputLayoutActiveRef.current &&
lastActiveFollowOutputLayoutRef.current &&
activeFollowOutputLayoutsEqual(lastActiveFollowOutputLayoutRef.current, layout),
);
resumedUnchangedLayoutRef.current = resumedUnchangedLayout;
pendingResumeGeometryCheckRef.current = resumedUnchangedLayout;
wasFollowOutputLayoutActiveRef.current = isActive;
if (!isActive) {
return;
}
lastActiveFollowOutputLayoutRef.current = layout;
if (!followOutputRef.current || resumedUnchangedLayout) return;
cancelPendingStickToBottom();
scrollMessagesToBottom("auto");
}, [
activationKey,
cancelPendingStickToBottom,
isActive,
isActivationReady,
renderLiveAuxiliary,
scrollMessagesToBottom,
segments.historyMounted,
segments.historyVirtualized,
segments.liveHead,
virtualTotalSize,
]);
useEffect(() => {
if (!isActive) {
return;
}
const resumedUnchangedLayout = resumedUnchangedLayoutRef.current;
resumedUnchangedLayoutRef.current = false;
if (!resumedUnchangedLayout) {
updateScrollMetrics();
}
evaluateHistoryStart();
if (isHistoryStartSettling()) {
scheduleHistoryStartPrependSettle();
}
}, [
evaluateHistoryStart,
hasOlderHistory,
isActive,
isAuthoritativeHistoryReady,
isLoadingOlderHistory,
olderHistoryProgressKey,
scheduleHistoryStartPrependSettle,
isHistoryStartSettling,
segments.historyMounted.length,
segments.historyVirtualized.length,
segments.liveHead.length,
updateScrollMetrics,
virtualTotalSize,
]);
useLayoutEffect(() => {
if (!isActive) {
return;
}
const scrollContainer = scrollContainerRef.current;
const contentNode = contentRef.current;
if (!scrollContainer || typeof ResizeObserver === "undefined") {
return;
}
if (!pendingResumeGeometryCheckRef.current) {
updateScrollMetrics();
evaluateHistoryStart();
}
const observer = new ResizeObserver(() => {
flushSync(() => {
measureVirtualizedRows();
});
const nextGeometry = getObservedViewportGeometry(scrollContainer);
if (pendingResumeGeometryCheckRef.current) {
pendingResumeGeometryCheckRef.current = false;
reportReadingPosition();
const previousGeometry = lastObservedViewportGeometryRef.current;
lastObservedViewportGeometryRef.current = nextGeometry;
if (previousGeometry && observedViewportGeometriesEqual(previousGeometry, nextGeometry)) {
return;
}
} else {
lastObservedViewportGeometryRef.current = nextGeometry;
}
reconcileReadingPosition();
if (isHistoryStartSettling()) {
scheduleHistoryStartPrependSettle();
}
updateScrollMetrics();
evaluateHistoryStart();
if (!followOutputRef.current) {
return;
}
// ResizeObserver runs before paint. Following in the next frame exposes
// the newly grown row at the old offset for one painted frame.
forceStickToBottom();
});
observer.observe(scrollContainer);
if (contentNode) {
observer.observe(contentNode);
}
// Paced reveal commits inside a message without rerendering this viewport.
// Observe those commits too, so the next frame sees the grown content at the
// bottom instead of waiting for the resize notification after animation frames.
const contentChanges = new MutationObserver(() => {
if (isActiveRef.current && followOutputRef.current) forceStickToBottom();
});
if (contentNode)
contentChanges.observe(contentNode, { childList: true, characterData: true, subtree: true });
return () => {
observer.disconnect();
contentChanges.disconnect();
};
}, [
reconcileReadingPosition,
evaluateHistoryStart,
isActive,
reportReadingPosition,
scheduleHistoryStartPrependSettle,
isHistoryStartSettling,
forceStickToBottom,
updateScrollMetrics,
measureVirtualizedRows,
]);
useLayoutEffect(() => {
if (!isActive) {
return;
}
const scrollContainer = scrollContainerRef.current;
if (!scrollContainer) {
return;
}
const markUpwardViewportInput = () => {
markUpwardInputEvidence();
if (scrollContainer.scrollTop <= USER_SCROLL_DELTA_EPSILON) {
rearmHistoryStartFromUserIntent();
}
};
const handleWheel = (event: WheelEvent) => {
if (
!event.ctrlKey &&
event.deltaY < 0 &&
!canNestedScrollerConsumeUpwardInput(event.target, scrollContainer)
) {
markUpwardViewportInput();
}
};
const handleKeyDown = (event: KeyboardEvent) => {
if (!isUpwardViewportScrollKey(event)) {
return;
}
if (canNestedScrollerConsumeUpwardInput(event.target, scrollContainer)) {
return;
}
markUpwardViewportInput();
};
const handlePointerDown = (event: PointerEvent) => {
clearMouseScrollGesture();
if (
event.pointerType !== "mouse" ||
!event.isPrimary ||
(event.button !== 0 && event.button !== 1) ||
isEditableEventTarget(event.target)
) {
return;
}
if (event.button === 0) {
if (isVerticalScrollbarGutterPress(event, scrollContainer)) {
mouseScrollGestureRef.current = { kind: "scrollbar", pointerId: event.pointerId };
}
return;
}
mouseScrollGestureRef.current = {
kind: "autoscroll",
pointerId: event.pointerId,
lastClientY: event.clientY,
hasUpwardEvidence: false,
evidenceExpiryFrame: null,
};
};
const handlePointerMove = (event: PointerEvent) => {
const gesture = mouseScrollGestureRef.current;
if (!gesture || gesture.kind !== "autoscroll" || gesture.pointerId !== event.pointerId) {
return;
}
if (event.clientY < gesture.lastClientY - USER_SCROLL_DELTA_EPSILON) {
gesture.hasUpwardEvidence = true;
if (gesture.evidenceExpiryFrame !== null) {
window.cancelAnimationFrame(gesture.evidenceExpiryFrame);
}
gesture.evidenceExpiryFrame = window.requestAnimationFrame(() => {
if (mouseScrollGestureRef.current === gesture) {
mouseScrollGestureRef.current = null;
}
});
}
gesture.lastClientY = event.clientY;
};
const handlePointerEnd = (event: PointerEvent) => {
const gesture = mouseScrollGestureRef.current;
if (gesture?.pointerId === event.pointerId && gesture.kind === "scrollbar") {
clearMouseScrollGesture();
}
};
const handlePointerCancel = (event: PointerEvent) => {
if (mouseScrollGestureRef.current?.pointerId === event.pointerId) {
clearMouseScrollGesture();
}
};
const handleTouchStart = (event: TouchEvent) => {
const touch = event.touches[0];
if (!touch) {
return;
}
lastTouchClientYRef.current = touch.clientY;
};
const handleTouchMove = (event: TouchEvent) => {
const touch = event.touches[0];
if (!touch) {
return;
}
const previousTouchY = lastTouchClientYRef.current;
if (
previousTouchY !== null &&
touch.clientY > previousTouchY + 1 &&
!canNestedScrollerConsumeUpwardInput(event.target, scrollContainer)
) {
markUpwardViewportInput();
}
lastTouchClientYRef.current = touch.clientY;
};
const handleTouchEnd = () => {
lastTouchClientYRef.current = null;
};
// Read user movement before the virtualizer's bubbling listener flushes a
// layout correction. Scroll events reuse the last committed row geometry.
scrollContainer.addEventListener("scroll", handleDomScroll, { passive: true, capture: true });
scrollContainer.addEventListener("wheel", handleWheel, { passive: true });
scrollContainer.addEventListener("keydown", handleKeyDown, { passive: true });
scrollContainer.addEventListener("pointerdown", handlePointerDown, { passive: true });
window.addEventListener("pointermove", handlePointerMove, { passive: true });
window.addEventListener("pointerup", handlePointerEnd, { passive: true });
window.addEventListener("pointercancel", handlePointerCancel, { passive: true });
window.addEventListener("blur", clearMouseScrollGesture);
scrollContainer.addEventListener("touchstart", handleTouchStart, { passive: true });
scrollContainer.addEventListener("touchmove", handleTouchMove, { passive: true });
scrollContainer.addEventListener("touchend", handleTouchEnd, { passive: true });
scrollContainer.addEventListener("touchcancel", handleTouchEnd, { passive: true });
return () => {
scrollContainer.removeEventListener("scroll", handleDomScroll, true);
scrollContainer.removeEventListener("wheel", handleWheel);
scrollContainer.removeEventListener("keydown", handleKeyDown);
scrollContainer.removeEventListener("pointerdown", handlePointerDown);
window.removeEventListener("pointermove", handlePointerMove);
window.removeEventListener("pointerup", handlePointerEnd);
window.removeEventListener("pointercancel", handlePointerCancel);
window.removeEventListener("blur", clearMouseScrollGesture);
scrollContainer.removeEventListener("touchstart", handleTouchStart);
scrollContainer.removeEventListener("touchmove", handleTouchMove);
scrollContainer.removeEventListener("touchend", handleTouchEnd);
scrollContainer.removeEventListener("touchcancel", handleTouchEnd);
clearUpwardInputEvidence();
};
}, [
clearMouseScrollGesture,
clearUpwardInputEvidence,
handleDomScroll,
isActive,
markUpwardInputEvidence,
rearmHistoryStartFromUserIntent,
]);
useEffect(() => {
const handle: StreamViewportHandle = {
focus: () => scrollContainerRef.current?.focus({ preventScroll: true }),
scrollToBottom: () => {
setFollowOutput(true);
cancelPendingStickToBottom();
forceStickToBottom();
},
prepareForViewportChange: () => {
if (!followOutputRef.current) {
return;
}
scheduleStickToBottom();
},
holdRow: (rowId, apply, triggerEdge) => {
cancelPendingStickToBottom();
setFollowOutput(false);
const row = measureRows()?.find((candidate) => candidate.id === rowId);
const scrollTop = scrollContainerRef.current?.scrollTop;
if (row && scrollTop !== undefined) readingAnchor.pin(row, triggerEdge, scrollTop);
disclosurePendingRef.current = true;
apply();
},
scrollToMessage,
};
viewportRef.current = handle;
return () => {
if (viewportRef.current === handle) {
viewportRef.current = null;
}
cancelPendingStickToBottom();
};
}, [
cancelPendingStickToBottom,
forceStickToBottom,
measureRows,
readingAnchor,
scheduleStickToBottom,
scrollToMessage,
viewportRef,
]);
const contentContainerStyle = useMemo((): CSSProperties => {
return {
display: "flex",
flexDirection: "column",
minHeight: "100%",
paddingTop: CONTENT_PADDING_TOP_PX,
paddingBottom: 16,
paddingLeft: isMobileBreakpoint ? 8 : 16,
paddingRight: isMobileBreakpoint ? 8 : 16,
boxSizing: "border-box",
};
}, [isMobileBreakpoint]);
const scrollContainerStyle = useMemo((): CSSProperties => {
const overlayScrollbarEnabled = scrollEnabled && !isMobileBreakpoint;
return {
width: "100%",
height: "100%",
overflowX: "hidden",
overflowY: scrollEnabled ? "auto" : "hidden",
overscrollBehaviorY: "contain",
// The browser still anchors delayed image growth while following output.
// Detached reading has one owner: reconcileReadingPosition.
overflowAnchor: followOutput ? "auto" : "none",
scrollbarWidth: overlayScrollbarEnabled ? "none" : undefined,
opacity: historyStartPaginationState.visible ? 1 : 0,
};
}, [followOutput, historyStartPaginationState.visible, isMobileBreakpoint, scrollEnabled]);
const viewportStyle = useMemo(
(): CSSProperties => ({
position: "relative",
flex: 1,
minWidth: 0,
minHeight: 0,
}),
[],
);
const virtualRowsContainerStyle = useMemo(
(): CSSProperties => ({
height: virtualTotalSize,
flexShrink: 0,
}),
[virtualTotalSize],
);
const renderVirtualRowStyle = useCallback(
(start: number): CSSProperties => ({
position: "absolute",
top: 0,
left: 0,
display: "flex",
flexDirection: "column",
width: "100%",
transform: `translateY(${start - VIRTUALIZER_SCROLL_MARGIN_PX}px)`,
}),
[],
);
const mountedHistoryRows = useMemo(() => {
return segments.historyMounted.map((item, index) => (
<div
key={item.id}
data-history-row-id={item.id}
data-message-id={getStreamItemMessageId(item)}
data-plugin-row={item.kind === "plugin" ? "true" : undefined}
style={streamRowStyle}
>
<StreamRowContent
item={item}
index={index}
items={segments.historyMounted}
render={renderHistoryMountedRow}
/>
</div>
));
}, [renderHistoryMountedRow, segments.historyMounted]);
const liveHeadRows = useMemo(() => {
return segments.liveHead.map((item, index) => (
<div
key={item.id}
data-history-row-id={item.id}
data-message-id={getStreamItemMessageId(item)}
data-plugin-row={item.kind === "plugin" ? "true" : undefined}
style={streamRowStyle}
>
<StreamRowContent
item={item}
index={index}
items={segments.liveHead}
revision={liveHeadRowRevision}
render={renderLiveHeadRow}
/>
</div>
));
}, [liveHeadRowRevision, renderLiveHeadRow, segments.liveHead]);
const mountedRows = useMemo(
() => [...mountedHistoryRows, ...liveHeadRows],
[liveHeadRows, mountedHistoryRows],
);
const liveAuxiliary = useMemo(() => {
return renderLiveAuxiliary();
}, [renderLiveAuxiliary]);
const historyStartSlot = useMemo(() => {
const isLoadingOperation = isHistoryStartLoadingOperation(historyStartPaginationState);
return (
<div style={historyStartSlotStyle} data-testid="older-history-slot">
{isLoadingOperation && (
<div data-testid="load-older-history-spinner">
<ThemedLoadingSpinner size="small" uniProps={foregroundMutedColorMapping} />
</div>
)}
{!isLoadingOperation &&
historyStartPaginationState.status === "failed" &&
hasOlderHistory && (
<button type="button" onClick={rearmHistoryStartFromUserIntent}>
{t("paneFind.retry")}
</button>
)}
</div>
);
}, [historyStartPaginationState, hasOlderHistory, rearmHistoryStartFromUserIntent, t]);
const shouldRenderEmpty =
!boundary.hasMountedHistory &&
!boundary.hasVirtualizedHistory &&
!boundary.hasLiveHead &&
!liveAuxiliary;
return (
<div style={viewportStyle} data-window-content>
<div
ref={handleScrollContainerRef}
// Let clicks focus the feed for browser keyboard scrolling without adding a Tab stop.
tabIndex={-1}
data-testid="agent-chat-scroll"
data-overlay-scrollbar={scrollEnabled && !isMobileBreakpoint ? "true" : undefined}
id={`agent-chat-scroll-${shouldUseVirtualizer ? "web-dom-virtualized" : "web-dom-scroll"}`}
style={scrollContainerStyle}
>
<div ref={handleContentRef} style={contentContainerStyle}>
{historyStartSlot}
<div ref={rowsHostRef} style={streamRowsHostStyle}>
<div style={virtualRowsContainerStyle} />
{[
...virtualRows.map((virtualRow) => {
const item = segments.historyVirtualized[virtualRow.index];
if (!item) return null;
return (
<div
key={virtualRow.key}
data-index={virtualRow.index}
data-history-row-id={item.id}
data-message-id={getStreamItemMessageId(item)}
data-plugin-row={item.kind === "plugin" ? "true" : undefined}
ref={measureVirtualizedRowElement}
style={renderVirtualRowStyle(virtualRow.start)}
>
<StreamRowContent
item={item}
index={virtualRow.index}
items={segments.historyVirtualized}
render={renderHistoryVirtualizedRow}
/>
</div>
);
}),
...mountedRows,
]}
</div>
<div ref={auxiliaryRef} style={streamRowStyle}>
{liveAuxiliary}
</div>
{shouldRenderEmpty ? listEmptyComponent : null}
</div>
</div>
{!historyStartPaginationState.visible ? (
<div data-testid="agent-initial-fill" style={initialFillStyle}>
<ThemedLoadingSpinner size="large" uniProps={foregroundMutedColorMapping} />
</div>
) : null}
{scrollEnabled && !isMobileBreakpoint ? (
<DomOverlayScrollbar
scrollContainerRef={scrollContainerRef}
onUserScrollUp={stopFollowingOutputFromUserIntent}
/>
) : null}
</div>
);
}
export function createWebStreamStrategy(input: CreateWebStreamStrategyInput): StreamStrategy {
return createStreamStrategy({
render: (renderInput) => (
<WebStreamViewport {...renderInput} isMobileBreakpoint={input.isMobileBreakpoint} />
),
orderTailReverse: false,
orderHeadReverse: false,
assistantTurnTraversalStep: -1,
edgeSlot: "footer",
historyLiveBoundaryEdge: "last",
liveHeadHistoryBoundaryEdge: "first",
frameChildOrder: "content-then-footer",
bottomAnchorTransportBehavior: {
verificationDelayFrames: 0,
verificationRetryMode: "rescroll",
},
disableParentScrollOnInlineDetailsExpansion: false,
anchorBottomOnContentSizeChange: true,
animateManualScrollToBottom: false,
useVirtualizedList: false,
isNearBottom: (inputMetrics) => {
const distanceFromBottom = Math.max(
0,
inputMetrics.contentHeight - (inputMetrics.offsetY + inputMetrics.viewportHeight),
);
return distanceFromBottom <= inputMetrics.threshold;
},
getBottomOffset: (metrics) => Math.max(0, metrics.contentHeight - metrics.viewportHeight),
});
}