TypeScript
fix(web): keep the composer expanded until the thread can scroll (#9965)
Theo Brownec1d27e593b27
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 11226371172..5bba2212d5e 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -111,6 +111,7 @@ import { type LegendListRef } from "@legendapp/list/react";import {CHAT_TIMELINE_ANCHOR_OFFSET,getAnchoredTurnMetrics,+ timelineContentOverflowsViewport,type TimelineScrollMode,} from "./chat/timelineScrollAnchoring";import {@@ -1647,6 +1648,9 @@ export default function ChatView(props: ChatViewProps) {const [scrollToEndClearance, setScrollToEndClearance] = useState(0);const isAtEndRef = useRef(true);const isTimelineAtLogicalEnd = useCallback(() => isAtEndRef.current, []);+ // Whether the timeline's rows extend past the viewport above the composer.+ // The composer only rests when there is reading space to give back.+ const [timelineOverflows, setTimelineOverflows] = useState(false);const attachmentPreviewHandoffByMessageIdRef = useRef<Record<string, string[]>>({});const attachmentPreviewPromotionInFlightByMessageIdRef = useRef<Record<string, true>>({});const sendInFlightRef = useRef(false);@@ -4502,32 +4506,11 @@ export default function ChatView(props: ChatViewProps) {[composerTimelineInset],);const timelineRealContentOverflowsViewport = useCallback(- (list?: LegendListRef | null) => {- const resolvedList = list ?? legendListRef.current;- const state = resolvedList?.getState();- if (!resolvedList || !state || state.data.length === 0) {- return false;- }-- const lastRowIndex = state.data.length - 1;- const lastRowTop = state.positionAtIndex(lastRowIndex);- const lastRowHeight = state.sizeAtIndex(lastRowIndex);- if (- typeof lastRowTop !== "number" ||- typeof lastRowHeight !== "number" ||- !Number.isFinite(lastRowTop) ||- !Number.isFinite(lastRowHeight)- ) {- return false;- }-- const realContentBottom = lastRowTop + Math.max(1, lastRowHeight);- const visibleScrollLength = Math.max(- 0,- (state.scrollLength ?? 0) - composerTimelineInset - CHAT_TIMELINE_ANCHOR_OFFSET,- );- return realContentBottom > visibleScrollLength;- },+ (list?: LegendListRef | null) =>+ timelineContentOverflowsViewport((list ?? legendListRef.current)?.getState(), {+ composerInset: composerTimelineInset,+ anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET,+ }),[composerTimelineInset],);const pageScrollControllerRef = useRef<ReturnType<typeof createPageScrollController> | null>(@@ -7857,6 +7840,7 @@ export default function ChatView(props: ChatViewProps) {contentInsetEndAdjustment={composerTimelineInset}liveFollowEnabled={timelineLiveFollowEnabled}onIsAtEndChange={onIsAtEndChange}+ onContentOverflowChange={setTimelineOverflows}onToolOutputCollapsedAtEnd={onToolOutputCollapsedAtEnd}onManualNavigation={cancelTimelineLiveFollowForUserNavigation}hideEmptyPlaceholder={isDraftHeroState || threadDetailLoading}@@ -8003,6 +7987,7 @@ export default function ChatView(props: ChatViewProps) {onRestingControlsVisibilityChange={setRestingComposerControlsVisible}getTimelineScrollableNode={getTimelineScrollableNode}isTimelineAtLogicalEnd={isTimelineAtLogicalEnd}+ timelineOverflows={timelineOverflows}onComposerOverlayHeightChange={publishComposerOverlayHeight}onRestingChange={onComposerRestingChange}promptRef={promptRef}diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsxindex 10898e311ce..30acb44dd42 100644--- a/apps/web/src/components/chat/ChatComposer.tsx+++ b/apps/web/src/components/chat/ChatComposer.tsx@@ -1251,6 +1251,8 @@ export interface ChatComposerProps {onRestingControlsVisibilityChange: (visible: boolean) => void;getTimelineScrollableNode: () => HTMLElement | null;isTimelineAtLogicalEnd: () => boolean;+ /** Whether the timeline has more content than fits above the composer. */+ timelineOverflows: boolean;onComposerOverlayHeightChange: (height: number) => void;/*** Whether the desktop resting layout is active. Reported from a layout@@ -1361,6 +1363,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)onRestingControlsVisibilityChange,getTimelineScrollableNode,isTimelineAtLogicalEnd,+ timelineOverflows,onComposerOverlayHeightChange,onRestingChange,promptRef,@@ -3699,6 +3702,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)isScrollCollapsed: isComposerScrollCollapsed,hasExpandedChrome: composerHasExpandedChrome,collapseOnBlur: settings.composerCollapseOnBlur,+ timelineOverflows,});// The relocated controls live in the context strip whenever the composer is// collapsed for any reason, the desktop resting layout or the phonediff --git a/apps/web/src/components/chat/MessagesTimeline.test.tsx b/apps/web/src/components/chat/MessagesTimeline.test.tsxindex 16a0cbd83ce..21f30fa625d 100644--- a/apps/web/src/components/chat/MessagesTimeline.test.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.test.tsx@@ -279,6 +279,7 @@ describe("MessagesTimeline", () => {isScrollCollapsed: composer.isComposerScrollCollapsed,hasExpandedChrome: false,collapseOnBlur: true,+ timelineOverflows: true,});});return (diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsxindex 4854121b5a3..fa718bc1de9 100644--- a/apps/web/src/components/chat/MessagesTimeline.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.tsx@@ -113,7 +113,10 @@ import {} from "./ExpandedImagePreview";import { ProposedPlanCard } from "./ProposedPlanCard";import { ChangedFilesCard } from "./ChangedFilesTree";-import { CHAT_TIMELINE_ANCHOR_OFFSET } from "./timelineScrollAnchoring";+import {+ CHAT_TIMELINE_ANCHOR_OFFSET,+ timelineContentOverflowsViewport,+} from "./timelineScrollAnchoring";import { MessageCopyButton } from "./MessageCopyButton";import { PierreEntryIcon } from "./PierreEntryIcon";import { AssistantSelectionToolbar } from "./AssistantSelectionToolbar";@@ -335,6 +338,11 @@ interface MessagesTimelineProps {*/liveFollowEnabled: boolean;onIsAtEndChange: (isAtEnd: boolean) => void;+ /**+ * Whether the real rows extend past the viewport above the composer.+ * Reported after scrolls, row size changes, and viewport resizes.+ */+ onContentOverflowChange?: (overflows: boolean) => void;onToolOutputCollapsedAtEnd?: () => void;onManualNavigation: () => void;hideEmptyPlaceholder?: boolean;@@ -382,6 +390,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({contentInsetEndAdjustment,liveFollowEnabled,onIsAtEndChange,+ onContentOverflowChange,onToolOutputCollapsedAtEnd,onManualNavigation,hideEmptyPlaceholder = false,@@ -602,12 +611,49 @@ export const MessagesTimeline = memo(function MessagesTimeline({[anchoredEndSpace, contentInsetEndAdjustment],);+ const measureContentOverflow = useCallback(+ () =>+ timelineContentOverflowsViewport(listRef.current?.getState?.(), {+ composerInset: contentInsetEndAdjustment,+ anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET,+ }),+ [contentInsetEndAdjustment, listRef],+ );+ // LegendList lays rows out from layout effects, so a read on the next frame+ // sees the settled positions. One frame is shared across bursts of size+ // changes.+ const contentOverflowFrameRef = useRef<number | null>(null);+ const cancelContentOverflowFrame = useCallback(() => {+ if (contentOverflowFrameRef.current !== null) {+ cancelAnimationFrame(contentOverflowFrameRef.current);+ contentOverflowFrameRef.current = null;+ }+ }, []);+ const reportContentOverflow = useCallback(() => {+ if (!onContentOverflowChange || contentOverflowFrameRef.current !== null) return;+ contentOverflowFrameRef.current = requestAnimationFrame(() => {+ contentOverflowFrameRef.current = null;+ onContentOverflowChange(measureContentOverflow());+ });+ }, [measureContentOverflow, onContentOverflowChange]);+ useEffect(() => cancelContentOverflowFrame, [cancelContentOverflowFrame]);+ // The list's own layout effects have already run here, so estimated row+ // positions are in place. Reporting before the first paint lets a thread+ // open in its final composer layout instead of correcting it a frame later.+ // A frame scheduled with the previous inset would overwrite this read, so+ // it is dropped first.+ useLayoutEffect(() => {+ cancelContentOverflowFrame();+ onContentOverflowChange?.(measureContentOverflow());+ }, [cancelContentOverflowFrame, measureContentOverflow, onContentOverflowChange, rows.length]);+const handleScroll = useCallback(() => {const state = listRef.current?.getState?.();const isAtEnd = resolveTimelineIsAtEnd(state);if (isAtEnd !== undefined && !citationPositioning) {onIsAtEndChange(isAtEnd);}+ reportContentOverflow();if (!state || minimapItems.length === 0) {return;}@@ -630,7 +676,14 @@ export const MessagesTimeline = memo(function MessagesTimeline({strip.dataset.inView = inView ? "true" : "false";}- }, [citationPositioning, listRef, minimapItems, minimapStripMap, onIsAtEndChange]);+ }, [+ citationPositioning,+ listRef,+ minimapItems,+ minimapStripMap,+ onIsAtEndChange,+ reportContentOverflow,+ ]);useEffect(() => {const frame = requestAnimationFrame(handleScroll);@@ -649,6 +702,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({current === nextHasPersistentGutter ? current : nextHasPersistentGutter,);setMinimapHitStripWidth(resolveTimelineMinimapHitStripWidth(viewportWidth));+ reportContentOverflow();};const frame = requestAnimationFrame(measure);@@ -660,7 +714,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({cancelAnimationFrame(frame);observer.disconnect();};- }, [timelineViewportElement, rows.length]);+ }, [timelineViewportElement, rows.length, reportContentOverflow]);const sharedState = useMemo<TimelineRowSharedState>(() => ({@@ -789,6 +843,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({}maintainScrollAtEndThreshold={1}onScroll={handleScroll}+ onItemSizeChanged={reportContentOverflow}className={cn("scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 [overflow-anchor:none] sm:px-5",topFadeEnabled && "topbar-scroll-fade",diff --git a/apps/web/src/components/chat/timelineScrollAnchoring.test.tsx b/apps/web/src/components/chat/timelineScrollAnchoring.test.tsxindex 1bf82c47a61..e5a67d05e40 100644--- a/apps/web/src/components/chat/timelineScrollAnchoring.test.tsx+++ b/apps/web/src/components/chat/timelineScrollAnchoring.test.tsx@@ -1,5 +1,9 @@import { describe, expect, it } from "vite-plus/test";-import { getAnchoredTurnMetrics, getRowBottom } from "./timelineScrollAnchoring";+import {+ getAnchoredTurnMetrics,+ getRowBottom,+ timelineContentOverflowsViewport,+} from "./timelineScrollAnchoring";function buildState({positions,@@ -21,6 +25,37 @@ function buildState({};}+describe("timelineContentOverflowsViewport", () => {+ const inset = { composerInset: 100, anchorOffset: 24 };++ it("reports overflow from the last row, not the inset spacer", () => {+ const fits = buildState({ positions: [0, 200], sizes: [200, 300], scrollLength: 700 });+ expect(timelineContentOverflowsViewport(fits, inset)).toBe(false);++ const overflows = buildState({ positions: [0, 200], sizes: [200, 400], scrollLength: 700 });+ expect(timelineContentOverflowsViewport(overflows, inset)).toBe(true);+ });++ it("treats an empty or unmeasured list as fitting", () => {+ expect(timelineContentOverflowsViewport(undefined, inset)).toBe(false);+ expect(+ timelineContentOverflowsViewport(+ buildState({ positions: [0, 200], sizes: [200, 400], scrollLength: 0 }),+ inset,+ ),+ ).toBe(false);+ expect(timelineContentOverflowsViewport(buildState({ positions: [], sizes: [] }), inset)).toBe(+ false,+ );+ expect(+ timelineContentOverflowsViewport(+ buildState({ positions: [0, 200], sizes: [200, Number.NaN] }),+ inset,+ ),+ ).toBe(false);+ });+});+describe("timeline scroll anchoring", () => {it("measures row bottoms from LegendList row position and size", () => {const state = buildState({diff --git a/apps/web/src/components/chat/timelineScrollAnchoring.ts b/apps/web/src/components/chat/timelineScrollAnchoring.tsindex 4b011e23590..81d2c20fcb7 100644--- a/apps/web/src/components/chat/timelineScrollAnchoring.ts+++ b/apps/web/src/components/chat/timelineScrollAnchoring.ts@@ -37,6 +37,31 @@ export function getRowBottom(state: TimelineListMeasurementState, index: number)return top + Math.max(1, height);}+/**+ * Whether the timeline's real rows extend past the viewport left above the+ * composer. The list's own content length includes the composer inset+ * spacer, so this measures from the last row instead. Unknown row geometry+ * or an unmeasured viewport counts as fitting.+ */+export function timelineContentOverflowsViewport(+ state: TimelineListMeasurementState | undefined,+ input: { readonly composerInset: number; readonly anchorOffset: number },+): boolean {+ if (!state || !state.data || state.data.length === 0) {+ return false;+ }+ const scrollLength = state.scrollLength;+ if (typeof scrollLength !== "number" || !Number.isFinite(scrollLength) || scrollLength <= 0) {+ return false;+ }+ const lastBottom = getRowBottom(state, state.data.length - 1);+ if (lastBottom === null) {+ return false;+ }+ const visibleScrollLength = Math.max(0, scrollLength - input.composerInset - input.anchorOffset);+ return lastBottom > visibleScrollLength;+}+export function getAnchoredTurnMetrics({state,anchorIndex,diff --git a/apps/web/src/components/chat/useComposerFocusState.test.tsx b/apps/web/src/components/chat/useComposerFocusState.test.tsxindex e4bf38430e8..5d2ee7a3163 100644--- a/apps/web/src/components/chat/useComposerFocusState.test.tsx+++ b/apps/web/src/components/chat/useComposerFocusState.test.tsx@@ -20,6 +20,7 @@ function ComposerProbe({ isMobileViewport = false }: { isMobileViewport?: booleaisScrollCollapsed: state.isComposerScrollCollapsed,hasExpandedChrome: false,collapseOnBlur: true,+ timelineOverflows: true,});});return null;diff --git a/apps/web/src/components/composerFooterLayout.test.ts b/apps/web/src/components/composerFooterLayout.test.tsindex 82ef5850cc1..7c85ead29b2 100644--- a/apps/web/src/components/composerFooterLayout.test.ts+++ b/apps/web/src/components/composerFooterLayout.test.ts@@ -104,6 +104,7 @@ describe("shouldUseRestingComposerLayout", () => {isScrollCollapsed: false,hasExpandedChrome: false,collapseOnBlur: true,+ timelineOverflows: true,};it("uses the resting layout for an unfocused desktop composer", () => {@@ -131,6 +132,17 @@ describe("shouldUseRestingComposerLayout", () => {).toBe(true);});+ it("keeps the composer expanded while the timeline fits above it", () => {+ expect(shouldUseRestingComposerLayout({ ...resting, timelineOverflows: false })).toBe(false);+ expect(+ shouldUseRestingComposerLayout({+ ...resting,+ isScrollCollapsed: true,+ timelineOverflows: false,+ }),+ ).toBe(false);+ });+it("keeps new-thread composers expanded", () => {expect(shouldUseRestingComposerLayout({ ...resting, isExistingThread: false })).toBe(false);});diff --git a/apps/web/src/components/composerFooterLayout.ts b/apps/web/src/components/composerFooterLayout.tsindex b7b7d91a033..2747e72bb02 100644--- a/apps/web/src/components/composerFooterLayout.ts+++ b/apps/web/src/components/composerFooterLayout.ts@@ -30,6 +30,8 @@ export function shouldUseRestingComposerLayout(input: {isScrollCollapsed: boolean;hasExpandedChrome: boolean;collapseOnBlur: boolean;+ /** Whether the timeline has more content than fits above the composer. */+ timelineOverflows: boolean;}): boolean {// Passive draft content is deliberately absent here. Resting only clamps// the prompt row and overlays its actions; non-image attachment and context@@ -44,8 +46,18 @@ export function shouldUseRestingComposerLayout(input: {// the user asked for it with the gesture, and it lifts on the next// composer interaction. With blur collapse off, losing focus alone never// rests the composer.+ //+ // Resting exists to give reading space back to the timeline. A thread that+ // fits above the composer has nothing to reclaim, so it stays expanded and+ // never shows the collapsed row that a fresh thread would otherwise open on.const collapsed = input.isScrollCollapsed || (input.collapseOnBlur && !input.isFocused);- return input.isExistingThread && !input.isMobileViewport && collapsed && !input.hasExpandedChrome;+ return (+ input.isExistingThread &&+ !input.isMobileViewport &&+ input.timelineOverflows &&+ collapsed &&+ !input.hasExpandedChrome+ );}/**