{openState === 'loading' &&
{t('chat.loadingHistory')}
}
{openState === 'error' && openError !== null && (
@@ -776,7 +227,7 @@ export function ChatView({
)}
{hasMore && (
-
@@ -825,17 +276,13 @@ export function ChatView({
/>
))}
- {!atBottom && (
+ {!scroll.followingTail && (
{
- const local = listRef.current
- /* v8 ignore next -- ref-null guard: the button only renders alongside the mounted list. */
- if (local !== null) toBottom(scrollerOf(local))
- }}
+ onClick={scroll.returnToBottom}
>
diff --git a/packages/client/ui-chat/src/client/chat/use-chat-navigation.ts b/packages/client/ui-chat/src/client/chat/use-chat-navigation.ts
new file mode 100644
index 0000000000..d74de13d6d
--- /dev/null
+++ b/packages/client/ui-chat/src/client/chat/use-chat-navigation.ts
@@ -0,0 +1,209 @@
+/** Turn jumps and history-prepend anchoring, independent of DOM measurement. */
+import { useLayoutEffect, useState } from 'react'
+import type { SessionSeq } from '@deepseek-ai/dsh-session/types'
+import type { ChatNode } from '../contract/chat-nodes.ts'
+import type { ChatScrollPosition, ChatViewSlotProps } from '../contract/slots.ts'
+import type { TurnRailItem } from './turn-rail-items.ts'
+import type { ChatReading, ReadingSample } from './use-chat-reading.ts'
+import type { ChatViewport } from './use-chat-viewport.ts'
+
+/** History availability and loading operations for the committed Chat window. */
+export interface ChatNavigationInput extends Pick
{
+ readonly firstSeq: ChatNode['anchorSeq'] | null
+ readonly hasMore: boolean
+ readonly loadingOlder: boolean
+}
+
+interface TurnJump {
+ readonly turn: number
+ readonly seq: SessionSeq
+ phase: 'loading' | 'settled'
+ landing: 'pending' | 'landed' | 'interrupted'
+ repageHead: ChatNavigationInput['firstSeq']
+}
+
+/** Owns one replaceable turn jump and the anchor retained while history loads. */
+export class ChatNavigation {
+ private jump: TurnJump | null = null
+ private anchor: ChatScrollPosition | null = null
+ private committed: Pick
+ private settleFrame: number | null = null
+
+ constructor(
+ private readonly viewport: ChatViewport,
+ private readonly reading: ChatReading,
+ private input: ChatNavigationInput,
+ private readonly onBusyTurn: (turn: number | null) => void,
+ ) {
+ this.committed = input
+ }
+
+ /**
+ * Adopt committed history availability without starting a request.
+ * @param input - history state from the latest committed render.
+ */
+ setInput(input: ChatNavigationInput): void { this.input = input }
+
+ /** Cancel navigation and establish the current history window as the baseline. */
+ reset(): void {
+ this.cancel()
+ this.committed = this.input
+ }
+
+ /** Cancel local callbacks; late history completions cannot revive a task. */
+ dispose(): void {
+ this.clearTask()
+ }
+
+ /** Release the jump, paging anchor, and busy indicator without cancelling shared history I/O. */
+ cancel(): void {
+ this.clearTask()
+ this.onBusyTurn(null)
+ }
+
+ private clearTask(): void {
+ this.cancelFrame()
+ this.jump = null
+ this.anchor = null
+ }
+
+ /**
+ * Replace the current jump with an explicit turn selection.
+ * @param item - loaded anchor or unloaded turn to fetch before landing.
+ */
+ readonly navigateToTurn = (item: TurnRailItem): void => {
+ if (item.anchor.kind === 'loaded') {
+ const landing = this.viewport.scrollToTurn(item.turn)
+ if (landing === null) return
+ this.cancel()
+ this.reading.acceptNavigation(landing)
+ this.anchor = this.input.loadingOlder ? landing.position : null
+ return
+ }
+ this.cancelFrame()
+ this.anchor = this.viewport.capturePosition()
+ this.reading.pauseFollowing()
+ const jump: TurnJump = {
+ turn: item.turn,
+ seq: item.anchor.seq,
+ phase: 'loading',
+ landing: 'pending',
+ repageHead: null,
+ }
+ this.jump = jump
+ this.onBusyTurn(jump.turn)
+ this.request(jump)
+ }
+
+ /** Request one older page while retaining the current semantic position. */
+ readonly loadEarlier = (): void => {
+ this.anchor = this.viewport.capturePosition()
+ this.input.loadOlder()
+ }
+
+ /**
+ * Preserve reader ownership across pending history work.
+ * @param sample - settled reader movement that can update or interrupt an anchor.
+ */
+ readerSampled(sample: ReadingSample): void {
+ if (sample.movedByReader && this.jump?.landing === 'landed') this.jump.landing = 'interrupted'
+ if (sample.followingTail) this.anchor = null
+ else if (this.anchor !== null && sample.position !== null) this.anchor = sample.position
+ }
+
+ /**
+ * Reconcile a newly committed history head with any retained anchor.
+ * @returns whether a prepended window consumed the current position-preservation operation.
+ */
+ contentCommitted(): boolean {
+ const previous = this.committed
+ this.committed = this.input
+ if (this.anchor !== null && this.input.firstSeq !== null && previous.firstSeq !== null
+ && this.input.firstSeq < previous.firstSeq) {
+ if (this.landJump(false)) return true
+ const landing = this.viewport.preserve(this.anchor)
+ this.anchor = this.jump === null ? null : landing?.position ?? null
+ if (landing !== null) this.reading.preservePosition(landing)
+ return true
+ }
+ if (previous.loadingOlder && !this.input.loadingOlder && this.jump === null) this.anchor = null
+ return false
+ }
+
+ /** Land, retry, or complete the current jump against the committed window. */
+ reconcile(): void {
+ const jump = this.jump
+ if (jump === null || this.reading.pending) return
+ if (jump.phase === 'loading') {
+ if (jump.landing === 'pending') this.landJump(false)
+ return
+ }
+ if (this.input.loadingOlder) return
+ if (this.landJump(true)) return
+ const uncovered = this.input.firstSeq === null || this.input.firstSeq > jump.seq
+ if (uncovered && this.input.hasMore && jump.repageHead !== this.input.firstSeq) {
+ jump.repageHead = this.input.firstSeq
+ this.anchor = this.viewport.capturePosition()
+ this.request(jump)
+ return
+ }
+ const fallback = this.viewport.scrollToTurnAtOrAfter(jump.turn)
+ this.cancel()
+ if (fallback !== null) this.reading.acceptNavigation(fallback)
+ }
+
+ private landJump(settle: boolean): boolean {
+ const jump = this.jump
+ if (jump === null) return false
+ if (jump.landing === 'interrupted') {
+ if (settle) { this.cancel(); return true }
+ return false
+ }
+ const landing = this.viewport.scrollToTurn(jump.turn)
+ if (landing === null) return false
+ this.reading.acceptNavigation(landing)
+ if (settle) this.cancel()
+ else {
+ this.anchor = landing.position
+ jump.landing = 'landed'
+ }
+ return true
+ }
+
+ private request(jump: TurnJump): void {
+ jump.phase = 'loading'
+ const settled = (): void => {
+ if (this.jump !== jump) return
+ jump.phase = 'settled'
+ this.cancelFrame()
+ if (typeof requestAnimationFrame !== 'function') this.reconcile()
+ else this.settleFrame = requestAnimationFrame(() => {
+ this.settleFrame = null
+ if (this.jump === jump) this.reconcile()
+ })
+ }
+ void this.input.loadThrough(jump.seq).then(settled, settled)
+ }
+
+ private cancelFrame(): void {
+ if (this.settleFrame !== null && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(this.settleFrame)
+ this.settleFrame = null
+ }
+}
+
+/**
+ * Retain one navigation owner for the component's lifetime.
+ * @param viewport - turn-aware DOM operations.
+ * @param reading - reading and follow policy receiving navigation landings.
+ * @param input - committed history state and load operations.
+ * @returns the navigation owner and its visible busy turn.
+ */
+export function useChatNavigation(
+ viewport: ChatViewport, reading: ChatReading, input: ChatNavigationInput,
+): { navigation: ChatNavigation; busyTurn: number | null } {
+ const [busyTurn, setBusyTurn] = useState(null)
+ const [navigation] = useState(() => new ChatNavigation(viewport, reading, input, setBusyTurn))
+ useLayoutEffect(() => { navigation.setInput(input) }, [navigation, input])
+ useLayoutEffect(() => () => { navigation.dispose() }, [navigation])
+ return { navigation, busyTurn }
+}
diff --git a/packages/client/ui-chat/src/client/chat/use-chat-reading.ts b/packages/client/ui-chat/src/client/chat/use-chat-reading.ts
new file mode 100644
index 0000000000..9142541556
--- /dev/null
+++ b/packages/client/ui-chat/src/client/chat/use-chat-reading.ts
@@ -0,0 +1,228 @@
+/** Follow-tail ownership, saved-position restoration, and sampled reader movement. */
+import { useLayoutEffect, useState } from 'react'
+import type { ChatScrollPosition, ChatViewSlotProps } from '../contract/slots.ts'
+import type { ChatViewport, ViewportLanding, ViewportMetrics, ViewportScroll } from './use-chat-viewport.ts'
+
+const FOLLOW_THRESHOLD = 24
+const SCROLL_SAMPLE_INTERVAL_MS = 500
+
+/** Reading facts that affect Chat chrome and initial rail placement. */
+export interface ChatReadingState {
+ readonly initialized: boolean
+ readonly followingTail: boolean
+ readonly activeTurn: number | null
+}
+
+/** Settled reader position delivered to history-navigation policy. */
+export interface ReadingSample {
+ readonly position: ChatScrollPosition | null
+ readonly movedByReader: boolean
+ readonly followingTail: boolean
+}
+
+type PositionStore = ChatViewSlotProps['chatScroll']
+
+/** Owns reading policy and its cancellable sampling work, without DOM access. */
+export class ChatReading {
+ private sampleTimer: number | null = null
+ private probeFrame: number | null = null
+ private sampled: ((sample: ReadingSample) => void) | null = null
+
+ constructor(
+ private readonly viewport: ChatViewport,
+ private store: PositionStore,
+ private state: ChatReadingState,
+ private readonly onChange: (state: ChatReadingState) => void,
+ ) {}
+
+ /**
+ * Expose pending reader ownership to navigation and resize handlers.
+ * @returns whether reader input still awaits interval or scrollend sampling.
+ */
+ get pending(): boolean { return this.sampleTimer !== null }
+ /**
+ * Expose the active follow policy.
+ * @returns whether content growth retains bottom-follow ownership.
+ */
+ get followingTail(): boolean { return this.state.followingTail }
+
+ /**
+ * Adopt the committed Session's scroll memory.
+ * @param store - scroll memory for the current Session.
+ */
+ setStore(store: PositionStore): void { this.store = store }
+
+ /**
+ * Connect history policy to settled reading observations.
+ * @param sampled - receives settled reader positions.
+ * @returns a disposer that disconnects only this listener.
+ */
+ connect(sampled: (sample: ReadingSample) => void): () => void {
+ this.sampled = sampled
+ return () => { if (this.sampled === sampled) this.sampled = null }
+ }
+
+ /** Cancel timers and animation frames and detach the sample listener. */
+ dispose(): void {
+ this.cancelPending()
+ this.sampled = null
+ }
+
+ /** Release bottom follow and pending sampling for an explicit navigation. */
+ pauseFollowing(): void {
+ this.cancelPending()
+ this.publish({ ...this.state, followingTail: false })
+ }
+
+ /** Land at the current floor and clear saved reader position. */
+ followTail(): void {
+ const landing = this.viewport.scrollToBottom()
+ if (landing === null) return
+ this.cancelPending()
+ this.commit(landing, true, this.viewport.latestTurn)
+ }
+
+ /** Restore the Session's semantic position, or follow the tail when none is saved. */
+ restore(): void {
+ const saved = this.store.read()
+ if (saved === null) { this.followTail(); return }
+ const landing = this.viewport.restore(saved)
+ if (landing === null) return
+ this.cancelPending()
+ const following = this.nearBottom(landing.metrics)
+ this.commit(landing, following, following ? this.viewport.latestTurn : this.state.activeTurn, following)
+ if (!this.state.followingTail && landing.position === null) {
+ const position = this.viewport.capturePosition()
+ if (position !== null) this.store.save(position)
+ }
+ this.refreshActiveTurn()
+ }
+
+ /**
+ * Adopt a known landing without rediscovering its anchor.
+ * @param landing - measured navigation result that replaces pending reader input.
+ */
+ acceptNavigation(landing: ViewportLanding): void {
+ this.cancelPending()
+ const following = this.nearBottom(landing.metrics)
+ this.commit(landing, following, landing.turn ?? (following ? this.viewport.latestTurn : this.state.activeTurn))
+ }
+
+ /**
+ * Retain reading policy while history changes the anchor's geometry.
+ * @param landing - compensated position that retains the current reading policy.
+ */
+ preservePosition(landing: ViewportLanding): void {
+ this.cancelPending()
+ this.commit(landing, this.state.followingTail, this.state.activeTurn)
+ }
+
+ /**
+ * Handle pinned layout movement immediately and defer genuine reader sampling.
+ * @param scroll - attributed scroll delivery; reader movement remains pending until sampled.
+ */
+ readonly onScroll = (scroll: ViewportScroll): void => {
+ if (this.state.followingTail && !scroll.movedByReader) {
+ this.followTail()
+ this.sampled?.({ position: null, movedByReader: false, followingTail: true })
+ return
+ }
+ this.sampleTimer ??= window.setTimeout(this.flushSample, SCROLL_SAMPLE_INTERVAL_MS)
+ }
+
+ /** Settle pending reader movement at the browser's scrollend. */
+ readonly onScrollEnd = (): void => { this.flushSample() }
+
+ /** Reconcile a layout change without overriding unsampled reader input. */
+ onResize(): void {
+ if (this.pending) return
+ if (this.state.followingTail) this.followTail()
+ else this.refreshActiveTurn()
+ }
+
+ /** Resolve the active turn from tail ownership or a coalesced reading-line probe. */
+ refreshActiveTurn(): void {
+ if (this.pending) return
+ if (this.state.followingTail) {
+ this.publish({ ...this.state, initialized: true, activeTurn: this.viewport.latestTurn })
+ return
+ }
+ if (this.probeFrame !== null) return
+ if (typeof requestAnimationFrame !== 'function') this.probe()
+ else this.probeFrame = requestAnimationFrame(this.probe)
+ }
+
+ private nearBottom(metrics: ViewportMetrics): boolean {
+ return metrics.floor - metrics.top <= FOLLOW_THRESHOLD + 1
+ }
+
+ private commit(
+ landing: ViewportLanding, followingTail: boolean, activeTurn: number | null, initialized = true,
+ ): void {
+ if (followingTail) this.store.save(null)
+ else if (landing.position !== null) this.store.save(landing.position)
+ this.publish({ initialized, followingTail, activeTurn })
+ }
+
+ private publish(state: ChatReadingState): void {
+ if (state.initialized === this.state.initialized && state.followingTail === this.state.followingTail
+ && state.activeTurn === this.state.activeTurn) return
+ this.state = state
+ this.onChange(state)
+ }
+
+ private cancelPending(): void {
+ if (this.sampleTimer !== null) window.clearTimeout(this.sampleTimer)
+ if (this.probeFrame !== null && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(this.probeFrame)
+ this.sampleTimer = null
+ this.probeFrame = null
+ }
+
+ private readonly probe = (): void => {
+ this.probeFrame = null
+ if (this.pending) return
+ const scroll = this.viewport.readScroll()
+ if (scroll === null) return
+ const activeTurn = this.nearBottom(scroll.metrics) ? this.viewport.latestTurn : this.viewport.readVisibleTurn(scroll.metrics)
+ this.publish({ ...this.state, initialized: true, activeTurn })
+ }
+
+ private readonly flushSample = (): void => {
+ if (!this.pending) return
+ this.cancelPending()
+ const scroll = this.viewport.readScroll()
+ if (scroll === null) return
+ const followingTail = scroll.movedByReader ? this.nearBottom(scroll.metrics) : this.state.followingTail
+ let position: ChatScrollPosition | null = null
+ if (!scroll.movedByReader && followingTail) this.followTail()
+ else {
+ position = followingTail ? null : this.viewport.capturePosition()
+ this.viewport.acknowledge(scroll.metrics)
+ if (followingTail || position !== null) this.store.save(position)
+ const activeTurn = this.nearBottom(scroll.metrics) ? this.viewport.latestTurn : this.viewport.readVisibleTurn(scroll.metrics)
+ this.publish({ initialized: true, followingTail, activeTurn })
+ }
+ this.sampled?.({ position, movedByReader: scroll.movedByReader, followingTail })
+ }
+}
+
+/**
+ * Retain reading policy and expose only changes in visible reading state.
+ * @param viewport - turn-aware DOM operations.
+ * @param store - Session-owned semantic scroll memory.
+ * @param initialTurn - latest loaded turn before the first landing.
+ * @returns the reading owner and its React-visible state.
+ */
+export function useChatReading(
+ viewport: ChatViewport, store: PositionStore, initialTurn: number | null,
+): { reading: ChatReading; state: ChatReadingState } {
+ const [state, setState] = useState(() => ({
+ initialized: false,
+ followingTail: store.read() === null,
+ activeTurn: initialTurn,
+ }))
+ const [reading] = useState(() => new ChatReading(viewport, store, state, setState))
+ useLayoutEffect(() => { reading.setStore(store) }, [reading, store])
+ useLayoutEffect(() => () => { reading.dispose() }, [reading])
+ return { reading, state }
+}
diff --git a/packages/client/ui-chat/src/client/chat/use-chat-scroll.ts b/packages/client/ui-chat/src/client/chat/use-chat-scroll.ts
new file mode 100644
index 0000000000..529bc7c2ce
--- /dev/null
+++ b/packages/client/ui-chat/src/client/chat/use-chat-scroll.ts
@@ -0,0 +1,126 @@
+/** Composes viewport operations, reading policy, and history navigation for Chat. */
+import { useCallback, useLayoutEffect, useMemo, useRef, type RefObject } from 'react'
+import type { ChatSnapshot } from '../contract/snapshot.ts'
+import type { ChatViewSlotProps } from '../contract/slots.ts'
+import { useChatNavigation, type ChatNavigation, type ChatNavigationInput } from './use-chat-navigation.ts'
+import { useChatReading, type ChatReadingState } from './use-chat-reading.ts'
+import { useChatViewport } from './use-chat-viewport.ts'
+
+/** Committed content and Session operations used to reconcile scroll ownership. */
+export interface ChatScrollInput extends ChatNavigationInput {
+ readonly chatScroll: ChatViewSlotProps['chatScroll']
+ readonly ready: boolean
+ readonly order: readonly string[]
+ readonly lastKey: string | null
+ readonly lastIsUser: boolean
+ readonly steeringId: string | null
+ readonly submissionId: string | null
+ readonly running: boolean
+ readonly loadedTurns: ReturnType
+}
+
+interface ChatScrollState extends ChatReadingState {
+ readonly listRef: RefObject
+ readonly columnRef: RefObject
+ readonly busyTurn: number | null
+ readonly navigateToTurn: ChatNavigation['navigateToTurn']
+ readonly loadEarlier: ChatNavigation['loadEarlier']
+ readonly returnToBottom: () => void
+}
+
+/**
+ * Coordinate scroll policy after Chat content commits.
+ * @param input - current Chat content, scroll memory, and history operations.
+ * @returns element refs, visible reading state, and navigation callbacks.
+ */
+export function useChatScroll(input: ChatScrollInput): ChatScrollState {
+ const {
+ ready, order, firstSeq, lastKey, lastIsUser, steeringId, submissionId, running,
+ loadedTurns, chatScroll, hasMore, loadingOlder, loadOlder, loadThrough,
+ } = input
+ const { viewport, listRef, columnRef } = useChatViewport()
+ const { reading, state } = useChatReading(viewport, chatScroll, loadedTurns.at(-1)?.turn ?? null)
+ const navigationInput = useMemo(() => ({
+ firstSeq, loadingOlder, hasMore, loadOlder, loadThrough,
+ }), [firstSeq, loadingOlder, hasMore, loadOlder, loadThrough])
+ const { navigation, busyTurn } = useChatNavigation(viewport, reading, navigationInput)
+ const content = useRef<{ input: ChatScrollInput; applied: ChatScrollInput | null; opened: boolean }>({
+ input, applied: null, opened: false,
+ })
+
+ const processContent = useCallback(() => {
+ if (reading.pending) return
+ const current = content.current.input
+ const previous = content.current.applied
+ content.current.applied = current
+ if (current.ready && !content.current.opened) {
+ content.current.opened = true
+ navigation.reset()
+ reading.restore()
+ return
+ }
+ if (navigation.contentCommitted()) {
+ navigation.reconcile()
+ return
+ }
+ const ownInput = (current.lastIsUser && current.lastKey !== previous?.lastKey)
+ || (current.steeringId !== null && current.steeringId !== previous?.steeringId)
+ || (current.submissionId !== null && current.submissionId !== previous?.submissionId)
+ const tipChanged = previous === null || current.ready !== previous.ready
+ || current.firstSeq !== previous.firstSeq || current.lastKey !== previous.lastKey
+ || current.order.length !== previous.order.length || current.running !== previous.running
+ || current.steeringId !== previous.steeringId || current.submissionId !== previous.submissionId
+ if (ownInput || (tipChanged && reading.followingTail)) {
+ navigation.cancel()
+ reading.followTail()
+ } else navigation.reconcile()
+ }, [reading, navigation])
+
+ useLayoutEffect(() => {
+ const disconnectViewport = viewport.connect({
+ scroll: reading.onScroll,
+ scrollEnd: reading.onScrollEnd,
+ resize: () => {
+ reading.onResize()
+ navigation.reconcile()
+ },
+ })
+ const disconnectReading = reading.connect((sample) => {
+ navigation.readerSampled(sample)
+ processContent()
+ })
+ return () => {
+ disconnectViewport()
+ disconnectReading()
+ content.current.opened = false
+ content.current.applied = null
+ }
+ }, [viewport, reading, navigation, processContent])
+
+ useLayoutEffect(() => {
+ const previous = content.current.input
+ content.current.input = {
+ ready, order, lastKey, lastIsUser, steeringId, submissionId, running, loadedTurns, chatScroll, ...navigationInput,
+ }
+ viewport.updateTurns(loadedTurns)
+ const layoutChanged = previous.order !== order || previous.ready !== ready
+ if (layoutChanged) viewport.invalidate()
+ processContent()
+ if (layoutChanged) reading.refreshActiveTurn()
+ }, [
+ viewport, reading, processContent, navigationInput, ready, order, lastKey, lastIsUser,
+ steeringId, submissionId, running, loadedTurns, chatScroll,
+ ])
+
+ const returnToBottom = useCallback(() => {
+ navigation.cancel()
+ reading.followTail()
+ }, [navigation, reading])
+
+ return {
+ listRef, columnRef, ...state, busyTurn,
+ navigateToTurn: navigation.navigateToTurn,
+ loadEarlier: navigation.loadEarlier,
+ returnToBottom,
+ }
+}
diff --git a/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts b/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts
new file mode 100644
index 0000000000..b4c1735707
--- /dev/null
+++ b/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts
@@ -0,0 +1,346 @@
+/** Turn-aware DOM scrolling and geometry, without history-loading or follow policy. */
+import { useLayoutEffect, useRef, useState, type RefObject } from 'react'
+import type { ChatScrollPosition } from '../contract/slots.ts'
+import type { ChatSnapshot } from '../contract/snapshot.ts'
+
+/** Scroll position, maximum top, and viewport height from one geometry read. */
+export interface ViewportMetrics {
+ readonly top: number
+ readonly floor: number
+ readonly height: number
+}
+
+/** Scroll geometry attributed against the last acknowledged position. */
+export interface ViewportScroll {
+ readonly metrics: ViewportMetrics
+ readonly movedByReader: boolean
+}
+
+/** Actual clamped scroll result, including any known semantic anchor and turn. */
+export interface ViewportLanding {
+ readonly metrics: ViewportMetrics
+ readonly position: ChatScrollPosition | null
+ readonly turn: number | null
+}
+
+interface ViewportEvents {
+ scroll: (event: ViewportScroll) => void
+ scrollEnd: () => void
+ resize: () => void
+}
+
+interface ViewportElements {
+ readonly list: HTMLElement
+ readonly scroller: HTMLElement
+ readonly composer: HTMLElement | null
+}
+
+/** Owns one Chat scrollport's DOM operations, event listeners, and size observer. */
+export class ChatViewport {
+ private elements: ViewportElements | null = null
+ private observer: ResizeObserver | null = null
+ private events: ViewportEvents | null = null
+ private turns: ReturnType = []
+ private observation: { top: number; landing: ViewportLanding | null } = { top: 0, landing: null }
+
+ /**
+ * Bind to the containing scrollport and observe content and viewport sizes.
+ * @param list - Chat root inside an optional shared conversation scrollport.
+ * @param column - content column whose size changes invalidate cached landings.
+ */
+ attach(list: HTMLElement, column: HTMLElement): void {
+ this.detach()
+ const scroller = list.closest('[data-conversation-scroll]') ?? list
+ const composer = scroller.querySelector('[data-composer-seat]')
+ const elements = { list, scroller, composer }
+ this.elements = elements
+ scroller.addEventListener('scroll', this.onScroll, { passive: true })
+ scroller.addEventListener('scrollend', this.onScrollEnd, { passive: true })
+ if (typeof ResizeObserver !== 'undefined') {
+ this.observer = new ResizeObserver(() => {
+ if (this.elements !== elements) return
+ this.invalidate()
+ this.events?.resize()
+ })
+ this.observer.observe(column)
+ this.observer.observe(scroller)
+ if (composer !== null) this.observer.observe(composer)
+ }
+ }
+
+ /** Disconnect DOM resources and clear observations for the detached view. */
+ detach(): void {
+ this.elements?.scroller.removeEventListener('scroll', this.onScroll)
+ this.elements?.scroller.removeEventListener('scrollend', this.onScrollEnd)
+ this.observer?.disconnect()
+ this.observer = null
+ this.elements = null
+ this.events = null
+ this.turns = []
+ this.observation = { top: 0, landing: null }
+ }
+
+ /**
+ * Connect business policy without changing DOM listener ownership.
+ * @param events - business handlers for scroll and layout changes.
+ * @returns a disposer that disconnects only these handlers.
+ */
+ connect(events: ViewportEvents): () => void {
+ this.events = events
+ return () => { if (this.events === events) this.events = null }
+ }
+
+ /**
+ * Adopt the loaded turn anchors without querying the DOM.
+ * @param turns - ordered loaded turns from the committed Chat snapshot.
+ */
+ updateTurns(turns: ReturnType): void {
+ this.turns = turns
+ }
+
+ /**
+ * Resolve the tail from the committed turn index.
+ * @returns the latest loaded turn, or null for an empty window.
+ */
+ get latestTurn(): number | null {
+ return this.turns.at(-1)?.turn ?? null
+ }
+
+ /** Discard geometry-dependent landing knowledge while retaining scroll attribution. */
+ invalidate(): void {
+ this.observation.landing = null
+ }
+
+ /**
+ * Accept a sampled reader position without retaining a known landing.
+ * @param metrics - settled reader position used as the next attribution baseline.
+ */
+ acknowledge(metrics: ViewportMetrics): void {
+ this.observation = { top: metrics.top, landing: null }
+ }
+
+ /**
+ * Compare the current scroll geometry with the last acknowledged position.
+ * @returns current metrics and movement attribution, or null while detached.
+ */
+ readScroll(): ViewportScroll | null {
+ const metrics = this.metrics()
+ if (metrics === null) return null
+ return {
+ metrics,
+ movedByReader: Math.abs(metrics.top - Math.min(this.observation.top, metrics.floor)) > 0.5,
+ }
+ }
+
+ private metrics(): ViewportMetrics | null {
+ const scroller = this.elements?.scroller
+ if (scroller === undefined) return null
+ const height = scroller.clientHeight
+ return { top: scroller.scrollTop, height, floor: Math.max(0, scroller.scrollHeight - height) }
+ }
+
+ private anchor(key: string): HTMLElement | null {
+ if (this.elements === null) return null
+ for (const row of this.elements.list.querySelectorAll('[data-chat-anchor-key]:not([hidden])')) {
+ if (row.dataset.chatAnchorKey === key) return row
+ }
+ return null
+ }
+
+ /**
+ * Capture the reader's position using visible transcript rows.
+ * @returns a visible semantic anchor, or null when no anchor can be resolved.
+ */
+ capturePosition(): ChatScrollPosition | null {
+ const elements = this.elements
+ if (elements === null) return null
+ const { list, scroller, composer } = elements
+ const viewport = scroller.getBoundingClientRect()
+ const bottom = composer?.getBoundingClientRect().top ?? viewport.bottom
+ let anchor: HTMLElement | null = null
+ if (typeof document.elementsFromPoint === 'function' && bottom > viewport.top) {
+ const content = list.getBoundingClientRect()
+ const left = Math.max(viewport.left, content.left)
+ const right = Math.min(viewport.right, content.right)
+ for (const element of document.elementsFromPoint(left + Math.max(0, right - left) / 2, viewport.top + 1)) {
+ const row = element instanceof HTMLElement ? element.closest('[data-chat-anchor-key]') : null
+ if (row !== null && list.contains(row)) { anchor = row; break }
+ }
+ }
+ if (anchor === null) {
+ const rows = list.querySelectorAll(
+ '[data-chat-flow] > [data-chat-flow-key]:not(:empty):not([hidden])',
+ )
+ let low = 0
+ let high = rows.length
+ while (low < high) {
+ const middle = (low + high) >>> 1
+ if (rows.item(middle).getBoundingClientRect().bottom > viewport.top) high = middle
+ else low = middle + 1
+ }
+ const row = rows[low]
+ anchor = row !== undefined && row.getBoundingClientRect().top < bottom ? row : rows[0] ?? null
+ }
+ const key = anchor?.dataset.chatAnchorKey
+ return anchor === null || key === undefined ? null : {
+ anchorKey: key,
+ anchorTop: anchor.getBoundingClientRect().top - viewport.top,
+ scrollTop: scroller.scrollTop,
+ }
+ }
+
+ /**
+ * Resolve the active turn, reusing a known landing when its position is unchanged.
+ * @param metrics - reusable scroll metrics; omitted callers request a fresh read.
+ * @returns the loaded turn at the reading line, or null while detached or empty.
+ */
+ readVisibleTurn(metrics = this.metrics()): number | null {
+ const knownTurn = this.observation.landing?.turn
+ if (knownTurn != null && metrics?.top === this.observation.top) return knownTurn
+ const elements = this.elements
+ const first = this.turns[0]
+ if (elements === null || metrics === null || first === undefined) return null
+ const line = elements.scroller.getBoundingClientRect().top + Math.min(96, metrics.height * 0.2)
+ const content = elements.list.getBoundingClientRect()
+ let reading: number | null = null
+ if (typeof document.elementsFromPoint === 'function' && content.width > 0) {
+ for (const element of document.elementsFromPoint(content.left + content.width / 2, line)) {
+ const row = element instanceof HTMLElement ? element.closest('[data-chat-turn]') : null
+ const turn = Number(row?.dataset.chatTurn)
+ if (row !== null && elements.list.contains(row) && Number.isSafeInteger(turn)) { reading = turn; break }
+ }
+ }
+ if (reading === null) {
+ for (const row of elements.list.querySelectorAll('[data-chat-turn]')) {
+ if (row.getBoundingClientRect().top > line) break
+ const turn = Number(row.dataset.chatTurn)
+ if (Number.isSafeInteger(turn)) reading = turn
+ }
+ }
+ let result = first.turn
+ if (reading !== null) {
+ for (const item of this.turns) {
+ if (item.turn > reading) break
+ result = item.turn
+ }
+ }
+ return result
+ }
+
+ /**
+ * Align a known loaded turn and return its actual clamped position.
+ * @param turn - loaded turn to align below the scrollport's top edge.
+ * @returns the actual landing, or null when its anchor is unavailable.
+ */
+ scrollToTurn(turn: number): ViewportLanding | null {
+ const item = this.turns.find(candidate => candidate.turn === turn)
+ if (item === undefined) return null
+ const row = this.anchor(item.anchorKey)
+ return row === null ? null : this.align(row, 24, turn)
+ }
+
+ /**
+ * Align the nearest available fallback for an unavailable turn anchor.
+ * @param turn - minimum turn number for a mounted fallback row.
+ * @returns the fallback landing, or null when no eligible row exists.
+ */
+ scrollToTurnAtOrAfter(turn: number): ViewportLanding | null {
+ if (this.elements === null) return null
+ for (const row of this.elements.list.querySelectorAll('[data-chat-turn]:not([hidden])')) {
+ const candidate = Number(row.dataset.chatTurn)
+ if (Number.isSafeInteger(candidate) && candidate >= turn) return this.align(row, 24, candidate)
+ }
+ return null
+ }
+
+ /**
+ * Restore a semantic anchor with a raw-position fallback.
+ * @param position - semantic scroll memory; raw top is used only if its row is absent.
+ * @returns the actual landing, or null while detached.
+ */
+ restore(position: ChatScrollPosition): ViewportLanding | null {
+ const row = this.anchor(position.anchorKey)
+ if (row !== null) return this.align(row, position.anchorTop, null)
+ const metrics = this.metrics()
+ return metrics === null ? null : this.write(position.scrollTop, metrics, null)
+ }
+
+ /**
+ * Preserve an existing anchor without falling back to an unrelated row.
+ * @param position - semantic anchor to retain after content changes.
+ * @returns the compensated landing, or null if the anchor is unavailable.
+ */
+ preserve(position: ChatScrollPosition): ViewportLanding | null {
+ const row = this.anchor(position.anchorKey)
+ return row === null ? null : this.align(row, position.anchorTop, null)
+ }
+
+ /**
+ * Align the scrollport with its current floor.
+ * @returns the actual floor landing, or null while detached.
+ */
+ scrollToBottom(): ViewportLanding | null {
+ const metrics = this.metrics()
+ return metrics === null ? null : this.write(metrics.floor, metrics, this.latestTurn)
+ }
+
+ private align(row: HTMLElement, offset: number, turn: number | null): ViewportLanding | null {
+ const metrics = this.metrics()
+ if (metrics === null || this.elements === null) return null
+ const top = row.getBoundingClientRect().top - this.elements.scroller.getBoundingClientRect().top
+ return this.write(metrics.top + top - offset, metrics, turn, { key: row.dataset.chatAnchorKey, top })
+ }
+
+ private write(
+ target: number, metrics: ViewportMetrics, turn: number | null,
+ anchor?: { key: string | undefined; top: number },
+ ): ViewportLanding | null {
+ if (this.elements === null) return null
+ const top = Math.max(0, Math.min(metrics.floor, target))
+ if (top !== metrics.top) this.elements.scroller.scrollTop = top
+ const actual = this.elements.scroller.scrollTop
+ const landing: ViewportLanding = {
+ metrics: { ...metrics, top: actual },
+ turn,
+ position: anchor?.key === undefined ? null : {
+ anchorKey: anchor.key,
+ anchorTop: anchor.top - (actual - metrics.top),
+ scrollTop: actual,
+ },
+ }
+ this.observation = { top: actual, landing }
+ return landing
+ }
+
+ private readonly onScroll = (event: Event): void => {
+ if (this.elements === null || event.target !== this.elements.scroller) return
+ if (this.observation.landing !== null && this.elements.scroller.scrollTop === this.observation.top) return
+ this.invalidate()
+ const scroll = this.readScroll()
+ if (scroll !== null) this.events?.scroll(scroll)
+ }
+
+ private readonly onScrollEnd = (event: Event): void => {
+ if (event.target === this.elements?.scroller) this.events?.scrollEnd()
+ }
+}
+
+/**
+ * Bind viewport resource ownership to the component's layout lifetime.
+ * @returns one viewport owner and the element refs attached for this mount.
+ */
+export function useChatViewport(): {
+ viewport: ChatViewport
+ listRef: RefObject
+ columnRef: RefObject
+} {
+ const listRef = useRef(null)
+ const columnRef = useRef(null)
+ const [viewport] = useState(() => new ChatViewport())
+ useLayoutEffect(() => {
+ if (listRef.current === null || columnRef.current === null) return
+ viewport.attach(listRef.current, columnRef.current)
+ return () => { viewport.detach() }
+ }, [viewport])
+ return { viewport, listRef, columnRef }
+}
diff --git a/packages/client/ui-chat/tests/chat-view.client.spec.tsx b/packages/client/ui-chat/tests/chat-view.client.spec.tsx
index c0fccd3ca7..3e7026d33c 100644
--- a/packages/client/ui-chat/tests/chat-view.client.spec.tsx
+++ b/packages/client/ui-chat/tests/chat-view.client.spec.tsx
@@ -45,18 +45,21 @@ import { formatRunDuration } from '../src/client/chat/message-chrome.ts'
import { ChatSnapshotBuilder } from '../src/client/conversation-nodes/chat-snapshot-builder.ts'
import type { TurnProcessSpec } from '../src/client/contract/turn-process.ts'
import { chatSnapshotFixture } from './chat-snapshot-fixture.client.ts'
+import { installTurnNavigatorObserver } from './turn-navigator-fixture.ts'
// Every session-scope fixture carries the resource hook the resources plugin merges into GlobalStandardProps.
const useResource = (() => ({ status: 'none' as const, value: undefined, failure: undefined })) as GlobalStandardProps['useResource']
afterEach(() => {
cleanup()
+ vi.restoreAllMocks()
vi.unstubAllGlobals()
})
// Keyless create() persists under the bare declared key; clear between cases
// so one harness's selection cannot rehydrate into the next.
beforeEach(() => {
localStorage.clear()
+ installTurnNavigatorObserver()
})
const SID = 's1' as SessionId
@@ -601,7 +604,7 @@ describe('ChatView', () => {
expect(railRenders).toBe(afterMount)
})
- it('projects loaded turns into prompt and response navigation previews', () => {
+ it('projects loaded turns into prompt and response navigation previews', async () => {
const snapshot = chatSnapshotFixture({
nodes: [
userInTurn(1, 'first prompt', 1),
@@ -618,11 +621,11 @@ describe('ChatView', () => {
const h = makeHarness({}, {}, snapshot)
const view = render()
const navigation = view.getByRole('navigation', { name: '轮次导航' })
- expect(navigation.style.getPropertyValue('--turn-natural-height')).toBe('22px')
- const first = view.getByRole('button', { name: '跳转到第 1 轮' })
+ const first = await view.findByRole('button', { name: '跳转到第 1 轮' })
+ expect(within(navigation).getAllByRole('button').map(mark => mark.getAttribute('aria-label'))).toEqual([
+ '跳转到第 1 轮', '跳转到第 2 轮',
+ ])
const second = view.getByRole('button', { name: '跳转到第 2 轮' })
- expect(first.parentElement?.style.getPropertyValue('--turn-natural-position')).toBe('0px')
- expect(second.parentElement?.style.getPropertyValue('--turn-natural-position')).toBe('10px')
expect(second.getAttribute('aria-current')).toBe('true')
fireEvent.focus(first)
const preview = view.getByRole('tooltip')
@@ -630,16 +633,14 @@ describe('ChatView', () => {
expect(preview.textContent).toContain('first response')
})
- it('jumps to a turn anchor and reflows stable marks after an older page arrives', () => {
+ it('jumps to a turn anchor and reflows stable marks after an older page arrives', async () => {
const later = [
userInTurn(4, 'second prompt', 2), assistant(5, 'second response', 2),
userInTurn(7, 'third prompt', 3), assistant(8, 'third response', 3),
]
const h = makeHarness({ nodes: later }, { hasMore: true })
const view = render()
- const second = view.getByRole('button', { name: '跳转到第 2 轮' })
- const secondPosition = second.parentElement as HTMLElement
- expect(secondPosition.style.getPropertyValue('--turn-natural-position')).toBe('0px')
+ const second = await view.findByRole('button', { name: '跳转到第 2 轮' })
const scroller = view.container.querySelector('[class*="scroll"]') as HTMLDivElement
const metrics = installScrollMetrics(scroller, 1_000, 300)
@@ -658,9 +659,10 @@ describe('ChatView', () => {
})
})
const movedSecond = view.getByRole('button', { name: '跳转到第 2 轮' })
- expect(movedSecond.parentElement).toBe(secondPosition)
- // Fixed pitch: the mark moves one slot down and never compresses.
- expect(secondPosition.style.getPropertyValue('--turn-natural-position')).toBe('10px')
+ expect(movedSecond).toBe(second)
+ expect(within(view.getByRole('navigation')).getAllByRole('button').map(mark => mark.getAttribute('aria-label'))).toEqual([
+ '跳转到第 1 轮', '跳转到第 2 轮', '跳转到第 3 轮',
+ ])
})
it('extends the rail with unloaded outline turns, pages on click, and falls back when nothing lands', async () => {
@@ -672,7 +674,7 @@ describe('ChatView', () => {
{ turn: 3, seq: 8, prompt: 'third prompt', response: 'third response' },
])
const view = render()
- const first = view.getByRole('button', { name: '加载并跳转到第 1 轮' })
+ const first = await view.findByRole('button', { name: '加载并跳转到第 1 轮' })
view.getByRole('button', { name: '加载并跳转到第 2 轮' })
const third = view.getByRole('button', { name: '跳转到第 3 轮' })
expect(third.getAttribute('aria-current')).toBe('true')
@@ -687,12 +689,48 @@ describe('ChatView', () => {
// The fake loader never delivers rows: settlement repages once for the
// unmoved head, then lands on the nearest rendered turn and un-busies.
- await act(async () => {})
+ await waitFor(() => { expect(first.getAttribute('aria-busy')).toBeNull() })
expect(h.loadThrough.mock.calls).toEqual([[0], [0]])
- expect(first.getAttribute('aria-busy')).toBeNull()
expect(view.getByRole('button', { name: '跳转到第 3 轮' }).getAttribute('aria-current')).toBe('true')
})
+ it('uses a known turn landing without hit testing or consuming rail scroll as transcript input', async () => {
+ const original = Object.getOwnPropertyDescriptor(document, 'elementsFromPoint')
+ const hitTest = vi.fn((): Element[] => [])
+ Object.defineProperty(document, 'elementsFromPoint', { configurable: true, value: hitTest })
+ try {
+ const h = makeHarness({ nodes: [
+ userInTurn(1, 'first', 1), assistant(2, 'first answer', 1),
+ userInTurn(4, 'second', 2), assistant(5, 'second answer', 2),
+ ] })
+ const view = render()
+ const first = await view.findByRole('button', { name: '跳转到第 1 轮' })
+ const scroller = view.container.querySelector('[class*="scroll"]') as HTMLDivElement
+ installScrollMetrics(scroller, 1_500, 300)
+ const row = view.container.querySelector('[data-chat-anchor-key="fixture:user:1"]') as HTMLElement
+ vi.spyOn(scroller, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 800, 300))
+ vi.spyOn(row, 'getBoundingClientRect').mockImplementation(() => new DOMRect(0, 100 - scroller.scrollTop, 800, 40))
+ readerScroll(scroller, 600)
+ scroller.scrollTop = 500
+ fireEvent.scroll(scroller)
+ hitTest.mockClear()
+
+ fireEvent.click(first)
+ fireEvent.scroll(scroller)
+ fireEvent(scroller, new Event('scrollend'))
+ const rail = view.getByRole('navigation').firstElementChild as HTMLElement
+ fireEvent.scroll(rail)
+ fireEvent(rail, new Event('scrollend', { bubbles: true }))
+
+ expect(scroller.scrollTop).toBe(76)
+ expect(first.getAttribute('aria-current')).toBe('true')
+ expect(hitTest).not.toHaveBeenCalled()
+ } finally {
+ if (original === undefined) Reflect.deleteProperty(document, 'elementsFromPoint')
+ else Object.defineProperty(document, 'elementsFromPoint', original)
+ }
+ })
+
it('a jump from the pinned tail releases bottom ownership so the follow snap cannot cancel it', async () => {
const later = [userInTurn(8, 'third prompt', 3), assistant(9, 'third response', 3)]
const h = makeHarness({ nodes: later }, { hasMore: true })
@@ -706,7 +744,7 @@ describe('ChatView', () => {
// Pinned to the tail on open: the back-to-bottom control is absent.
expect(view.queryByRole('button', { name: '回到底部' })).toBeNull()
- const first = view.getByRole('button', { name: '加载并跳转到第 1 轮' })
+ const first = await view.findByRole('button', { name: '加载并跳转到第 1 轮' })
fireEvent.click(first)
// The click itself leaves the tail...
expect(view.getByRole('button', { name: '回到底部' })).toBeTruthy()
@@ -726,7 +764,7 @@ describe('ChatView', () => {
{ turn: 3, seq: 8, prompt: 'third prompt', response: '' },
])
const view = render()
- const first = view.getByRole('button', { name: '加载并跳转到第 1 轮' })
+ const first = await view.findByRole('button', { name: '加载并跳转到第 1 轮' })
fireEvent.click(first)
// The session-side guard refuses the busy-pager jump instantly, yet the
// mark stays busy instead of degrading to the nearest loaded turn.
@@ -736,12 +774,11 @@ describe('ChatView', () => {
// The plain pull settles: the flip re-settles the jump, which repages.
act(() => { h.setSession({ loadingOlder: false }) })
- await act(async () => {})
+ await waitFor(() => { expect(first.getAttribute('aria-busy')).toBeNull() })
expect(h.loadThrough.mock.calls).toEqual([[0], [0]])
- expect(first.getAttribute('aria-busy')).toBeNull()
})
- it('scrolls the fixed-pitch rail inside its frame with gradient fades at the scrollable ends', () => {
+ it('scrolls the fixed-pitch rail inside its frame with gradient fades at the scrollable ends', async () => {
const h = makeHarness(
{ nodes: [userInTurn(8, 'latest prompt', 60), assistant(9, 'latest response', 60)] },
{ hasMore: true },
@@ -754,11 +791,11 @@ describe('ChatView', () => {
})))
const view = render()
const nav = view.getByRole('navigation', { name: '轮次导航' })
- // 60 marks at the fixed 10px pitch: the ladder keeps its natural height.
- expect(nav.style.getPropertyValue('--turn-natural-height')).toBe('602px')
const scroller = nav.querySelector('[class*="scroller"]') as HTMLElement
- Object.defineProperty(scroller, 'scrollHeight', { value: 602, configurable: true })
- Object.defineProperty(scroller, 'clientHeight', { value: 300, configurable: true })
+ const latest = await within(nav).findByRole('button', { name: '跳转到第 60 轮' })
+ expect(scroller.scrollTop).toBe(302)
+ expect(within(nav).getAllByRole('button').length).toBeLessThan(60)
+ expect(latest.getAttribute('aria-current')).toBe('true')
scroller.scrollTop = 0
fireEvent.scroll(scroller)
expect(scroller.className).toContain('fadeBottom')
@@ -768,12 +805,7 @@ describe('ChatView', () => {
fireEvent.scroll(scroller)
expect(scroller.className).toContain('fadeTop')
expect(scroller.className).toContain('fadeBottom')
- expect(nav.style.getPropertyValue('--turn-scroll-top')).toBe('150px')
-
- // Pointer mapping subtracts the rail scroll: y=94 with scrollTop 150 is
- // natural offset 238px → the 25th mark.
- vi.spyOn(nav, 'getBoundingClientRect').mockReturnValue({ top: 0 } as DOMRect)
- fireEvent.pointerMove(nav, { clientY: 94 })
+ fireEvent.pointerEnter(within(nav).getByRole('button', { name: '加载并跳转到第 25 轮' }))
expect(view.getByRole('tooltip').textContent).toContain('p25')
})
@@ -787,8 +819,18 @@ describe('ChatView', () => {
let releaseJump: (() => void) | undefined
h.loadThrough.mockImplementation(() => new Promise((resolve) => { releaseJump = resolve }))
const view = render()
+ const scroller = view.container.querySelector('[class*="scroll"]') as HTMLDivElement
+ installScrollMetrics(scroller, 1_000, 300)
+ scroller.scrollTop = 700
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) {
+ if (this.dataset.chatAnchorKey === 'fixture:user:0') {
+ const top = 100 - scroller.scrollTop
+ return { top, bottom: top + 40 } as DOMRect
+ }
+ return { top: 0, bottom: 300 } as DOMRect
+ })
- fireEvent.click(view.getByRole('button', { name: '加载并跳转到第 1 轮' }))
+ fireEvent.click(await view.findByRole('button', { name: '加载并跳转到第 1 轮' }))
expect(h.loadThrough).toHaveBeenCalledWith(0)
// The paged window commits: turn 1's rows and rail item enter the snapshot.
@@ -800,15 +842,14 @@ describe('ChatView', () => {
})
const first = view.getByRole('button', { name: '跳转到第 1 轮' })
expect(first.getAttribute('aria-current')).toBe('true')
+ expect(scroller.scrollTop).toBe(76)
// The mark stays busy until the jump settles: the loader's completion
// runs the final landing correction after the load-earlier button leaves.
expect(first.getAttribute('aria-busy')).toBe('true')
await act(async () => { releaseJump?.() })
- // Only the busy lifecycle is asserted after settlement: jsdom's zero
- // geometry makes the rAF active-turn resync read "at bottom" and hand the
- // mark to the last turn, so aria-current here is timing-dependent under
- // instrumentation; the landing position contract lives in the browser e2e.
- expect(first.getAttribute('aria-busy')).toBeNull()
+ await waitFor(() => { expect(first.getAttribute('aria-busy')).toBeNull() })
+ expect(first.getAttribute('aria-current')).toBe('true')
+ expect(scroller.scrollTop).toBe(76)
})
it('hands a windowless tool result to the Tool seat with an empty tool name', () => {
@@ -2365,7 +2406,7 @@ describe('ChatView', () => {
nodes: [user(1, 'old'), assistant(2, 'b'), user(5, 'later'), assistant(6, 'a'), user(9, 'mine')],
})
})
- expect(scroller.scrollTop).toBe(1600)
+ expect(scroller.scrollTop).toBe(1200)
})
it('back-to-bottom cancels an in-flight paging anchor', () => {
@@ -2379,7 +2420,7 @@ describe('ChatView', () => {
fireEvent.click(view.getByLabelText('回到底部'))
Object.defineProperty(scroller, 'scrollHeight', { value: 1_300, writable: true })
act(() => { h.setChat({ nodes: [assistant(2, 'older'), user(9, 'late')] }) })
- expect(scroller.scrollTop).toBe(1_300)
+ expect(scroller.scrollTop).toBe(1_100)
expect(h.chatScroll.read()).toBeNull()
})
@@ -2398,7 +2439,7 @@ describe('ChatView', () => {
})
expect(scroller.scrollTop).toBe(100)
fireEvent.click(backButton)
- expect(scroller.scrollTop).toBe(1000)
+ expect(scroller.scrollTop).toBe(700)
// At the bottom again: follow re-arms and the button unmounts.
expect(view.queryByLabelText('回到底部')).toBeNull()
})
@@ -2601,7 +2642,7 @@ describe('ChatView', () => {
it('one ResizeObserver owns pinned dynamic-height follow and ignores growth while away', () => {
let notify: (() => void) | undefined
- const observe = vi.fn()
+ const observe = vi.fn<(element: Element) => void>()
class ResizeObserverStub {
constructor(callback: ResizeObserverCallback) {
notify = () => { callback([], this as unknown as ResizeObserver) }
@@ -2621,15 +2662,17 @@ describe('ChatView', () => {
fireEvent(scroller, new Event('scrollend'))
Object.defineProperty(scroller, 'scrollHeight', { value: 1_200, writable: true })
act(() => { notify?.() })
- expect(scroller.scrollTop).toBe(1_200)
+ expect(scroller.scrollTop).toBe(900)
readerScroll(scroller, 200)
Object.defineProperty(scroller, 'scrollHeight', { value: 1_400, writable: true })
act(() => { notify?.() })
expect(scroller.scrollTop).toBe(200)
- expect(observe).toHaveBeenCalledTimes(1)
+ expect(observe.mock.calls.map(([element]) => element)).toEqual([
+ view.container.querySelector('[data-chat-flow]'), scroller,
+ ])
})
- it('pinned dynamic-height updates select the latest Turn without reading row geometry', () => {
+ it('pinned dynamic-height updates select the latest Turn without reading row geometry', async () => {
let notify: (() => void) | undefined
let nextFrame = 0
const frames = new Map()
@@ -2639,13 +2682,19 @@ describe('ChatView', () => {
return nextFrame
})
vi.stubGlobal('cancelAnimationFrame', (id: number) => { frames.delete(id) })
- class ResizeObserverStub {
+ const RailObserver = ResizeObserver
+ class ResizeObserverStub extends RailObserver {
+ private readonly onResize: () => void
+
constructor(callback: ResizeObserverCallback) {
- notify = () => { callback([], this as unknown as ResizeObserver) }
+ super(callback)
+ this.onResize = () => { callback([], this) }
}
- observe = vi.fn()
- disconnect = vi.fn()
+ override observe(element: Element): void {
+ super.observe(element)
+ if (element.closest('nav') === null) notify = this.onResize
+ }
}
vi.stubGlobal('ResizeObserver', ResizeObserverStub)
const rect = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect')
@@ -2658,6 +2707,7 @@ describe('ChatView', () => {
turnEnds: new Map([[1, 3], [2, 6]]),
})
const view = render()
+ await view.findByRole('button', { name: '跳转到第 2 轮' })
const scroller = view.container.querySelector('[class*="scroll"]') as HTMLDivElement
const metrics = installScrollMetrics(scroller, 1_000, 300)
scroller.scrollTop = 700
@@ -2705,11 +2755,11 @@ describe('ChatView', () => {
const h = makeHarness({ nodes: [user(1, 'q'), assistant(2, 'a')] })
const view = render(, { container: host })
// Open jump uses the host, not the local .scroll node.
- expect(host.scrollTop).toBe(2000)
+ expect(host.scrollTop).toBe(1500)
readerScroll(host, 100)
expect(view.getByLabelText('回到底部')).toBeTruthy()
fireEvent.click(view.getByLabelText('回到底部'))
- expect(host.scrollTop).toBe(2000)
+ expect(host.scrollTop).toBe(1500)
} finally {
host.remove()
}
@@ -2722,12 +2772,13 @@ describe('ChatView', () => {
Object.defineProperty(host, 'clientHeight', { value: 500, writable: true, configurable: true })
Object.defineProperty(host, 'scrollTop', { value: 0, writable: true, configurable: true })
document.body.appendChild(host)
- let anchorTop = 80
+ let anchorOffset = 180
vi.spyOn(host, 'getBoundingClientRect').mockImplementation(
() => ({ top: 0, bottom: 500 } as DOMRect),
)
const rect = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) {
if (this.dataset.chatAnchorKey === 'fixture:user:1') {
+ const anchorTop = anchorOffset - host.scrollTop
return { top: anchorTop, bottom: anchorTop + 40 } as DOMRect
}
return { top: 0, bottom: 40 } as DOMRect
@@ -2736,15 +2787,15 @@ describe('ChatView', () => {
const h = makeHarness({ nodes: [user(1, 'q'), assistant(2, 'a')] })
// Fresh open (nothing saved): the bottom jump stands.
const view = render(, { container: host })
- expect(host.scrollTop).toBe(2000)
+ expect(host.scrollTop).toBe(1500)
// Reader scrolls up; the position is recorded continuously.
readerScroll(host, 100)
// View-tab switch away and back: the view unmounts, then remounts.
view.rerender()
- anchorTop = 560
+ anchorOffset = 660
host.scrollTop = 0
view.rerender()
- expect(host.scrollTop).toBe(580) // approximate 100 + the row's 480px reflow shift
+ expect(host.scrollTop).toBe(580)
// The restored position is above the floor: follow stays disarmed.
expect(view.getByLabelText('回到底部')).toBeTruthy()
} finally {
@@ -2766,7 +2817,10 @@ describe('ChatView', () => {
})
document.body.appendChild(host)
const rect = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) {
- if (this.dataset.chatAnchorKey === 'fixture:user:1') return { top: 300, bottom: 340 } as DOMRect
+ if (this.dataset.chatAnchorKey === 'fixture:user:1') {
+ const top = 1_700 - host.scrollTop
+ return { top, bottom: top + 40 } as DOMRect
+ }
return { top: 0, bottom: 500 } as DOMRect
})
try {
@@ -2801,7 +2855,7 @@ describe('ChatView', () => {
view.rerender()
host.scrollTop = 0
view.rerender()
- expect(host.scrollTop).toBe(2000)
+ expect(host.scrollTop).toBe(1500)
} finally {
host.remove()
}