From 072ea695b9547aed7b0519e6575628508c68f3db Mon Sep 17 00:00:00 2001 From: imccyu Date: Sat, 19 Sep 2026 01:16:12 +0800 Subject: [PATCH] fix(chat): retain bottom follow during stream updates --- apps/web/tests/chat-scroll-contract.e2e.ts | 26 ++++++++++++++++++- packages/client/ui-chat/README.i18n.yaml | 4 +-- packages/client/ui-chat/README.md | 2 +- packages/client/ui-chat/README.zh.md | 2 +- .../src/client/chat/ChatView.module.css | 5 ++++ .../ui-chat/src/client/chat/ChatView.tsx | 2 +- .../src/client/chat/use-chat-reading.ts | 9 ++++--- .../ui-chat/tests/chat-view.client.spec.tsx | 21 +++++++++++++++ 8 files changed, 61 insertions(+), 10 deletions(-) diff --git a/apps/web/tests/chat-scroll-contract.e2e.ts b/apps/web/tests/chat-scroll-contract.e2e.ts index af9ebc875f..17485b10bc 100644 --- a/apps/web/tests/chat-scroll-contract.e2e.ts +++ b/apps/web/tests/chat-scroll-contract.e2e.ts @@ -93,6 +93,7 @@ interface ScrollWorld { interface ScrollWorldOptions { readonly failureShot: string + readonly paceMs?: number readonly replay?: ReplayOverrideDoc readonly seeds: readonly { fixture: ChatScrollFixture; id: string }[] } @@ -116,6 +117,22 @@ function textStream(first: string, done: string, deltaCount: number): StreamChun ] } +/** Hold replay text after the initial deltas until browser setup releases it. */ +function holdTextAfter(world: ScrollWorld, initialDeltas: number): () => void { + const gate = Promise.withResolvers() + const dispose = world.scaffold.ctx.on('llm/stream', async function* (_options, next) { + let deltas = 0 + for await (const chunk of next()) { + if (chunk.type === 'text-delta' && deltas++ === initialDeltas) await gate.promise + yield chunk + } + }) + return () => { + gate.resolve(undefined) + dispose() + } +} + function toolStream(): StreamChunk[] { const command = [ `: > ${TOOL_READY_FILE}`, @@ -159,7 +176,7 @@ async function launchScrollWorld(options: ScrollWorldOptions): Promise { }) const settled = world.scaffold.whenTurnSettled(60_000) + const releaseText = holdTextAfter(world, 1) try { const composer = world.page.locator('[data-composer-input][contenteditable="true"]').last() await composer.fill(LIVE_TEXT_PROMPT) @@ -551,6 +569,7 @@ describe('web e2e: long Chat scroll contract', () => { await wheelTranscript(world.page, 420) const readerAnchor = await visibleFlowAnchor(world.page) const chunksAfterAnchor = world.assistantFrames.filter(frame => frame.type === 'chunk').length + releaseText() await expect.poll( () => world.assistantFrames.filter(frame => frame.type === 'chunk').length, { timeout: 10_000 }, @@ -561,6 +580,7 @@ describe('web e2e: long Chat scroll contract', () => { await nextPaint(world.page) await expectSameFlowTop(world.page, readerAnchor) } finally { + releaseText() releaseHistory() } @@ -904,6 +924,7 @@ describe('web e2e: long Chat scroll contract', () => { it.skipIf(MODE === 'record')('touch-style fling scrolling owns streaming bottom-follow without wheel input', async () => { await withScrollWorld({ failureShot: 'web-e2e-chat-scroll-fling-stream', + paceMs: 0, replay: [ replayEntry(toolStream()), replayEntry(textStream(LIVE_FLING_FIRST, LIVE_FLING_DONE, 240)), @@ -915,6 +936,7 @@ describe('web e2e: long Chat scroll contract', () => { await openSeed(world.page, INPUTS_FIXTURE, INPUTS_FIXTURE.markers.assistant(INPUTS_FIXTURE.turns)) const backToBottom = world.page.getByRole('button', { name: 'Back to bottom', exact: true }) const settled = world.scaffold.whenTurnSettled(60_000) + const releaseText = holdTextAfter(world, 16) let released = false try { const composer = world.page.locator('[data-composer-input][contenteditable="true"]').last() @@ -952,12 +974,14 @@ describe('web e2e: long Chat scroll contract', () => { await expectBottom(world.page) await expect.poll(() => backToBottom.count(), { timeout: 10_000 }).toBe(0) const chunksAtRepin = world.assistantFrames.filter(frame => frame.type === 'chunk').length + releaseText() await expect.poll( () => world.assistantFrames.filter(frame => frame.type === 'chunk').length, { timeout: 15_000 }, ).toBeGreaterThan(chunksAtRepin + 5) await expectBottom(world.page) } finally { + releaseText() if (!released) await writeFile(releasePath, 'release\n').catch(() => {}) } diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml index d8e7c6416f..044e530fbc 100644 --- a/packages/client/ui-chat/README.i18n.yaml +++ b/packages/client/ui-chat/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-chat/README.md -README.md: 7f3d905b026edeb538de87dc5e54e0f05cd3c3bc -README.zh.md: 118fc29fdb4960dfc1606d7e9cd0a1ccaea9843d +README.md: 901c97e620a843d5d87964dbfe021c3e33e6fe3f +README.zh.md: 5500f0935c508b1ddce7113cf06003528fc1574b diff --git a/packages/client/ui-chat/README.md b/packages/client/ui-chat/README.md index 7f3d905b02..901c97e620 100644 --- a/packages/client/ui-chat/README.md +++ b/packages/client/ui-chat/README.md @@ -74,7 +74,7 @@ Settings → General exposes a persisted, localized `Normal` / `Compact` convers ## Scroll ownership -Chat restores semantic anchors across history prepend and renderer remounts. Pinned scroll deliveries without reader movement update follow ownership immediately, before subsequent layout changes can invalidate their floor. Reader movement remains pending until the sampling interval or `scrollend`, even inside the follow threshold, so layout growth cannot erase small scroll gestures. Submitting transcript input or steering immediately restores tail following and clears an older pending reader sample. While the reader is pinned to the floor, `ResizeObserver` follows the new floor and selects the latest loaded Turn without reading row geometry. Once the reader moves away, flow-height changes preserve the top position and the reading-line geometry selects the active Turn. Turn-rail previews paint above sticky Markdown code-block banners, while the rail frame remains inside the transcript band above the composer. +Chat restores semantic anchors across history prepend and renderer remounts, with browser scroll anchoring disabled on its scrollport only while following the tail. Pinned scroll deliveries without reader movement, and reader input that reaches the exact floor, update follow ownership immediately, before subsequent layout changes can invalidate their floor. Other reader movement remains pending until the sampling interval or `scrollend`, even inside the follow threshold, so layout growth cannot erase small scroll gestures. Submitting transcript input or steering immediately restores tail following and clears an older pending reader sample. While the reader is pinned to the floor, `ResizeObserver` follows the new floor and selects the latest loaded Turn without reading row geometry. Once the reader moves away, flow-height changes preserve the top position and the reading-line geometry selects the active Turn. Turn-rail previews paint above sticky Markdown code-block banners, while the rail frame remains inside the transcript band above the composer. The turn rail mounts only visible marks, overscan, and the focused mark's neighbors. Its fixed pitch and observed viewport size determine scroll offsets without reading the DOM scroll extent. Initial placement waits for the body's restored active Turn and the rail's first usable viewport size. The ref controls activate a Turn or scroll the rail independently; the transcript itself remains fully mounted. diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md index 118fc29fdb..5500f0935c 100644 --- a/packages/client/ui-chat/README.zh.md +++ b/packages/client/ui-chat/README.zh.md @@ -74,7 +74,7 @@ Assistant Markdown 中的 HTTP(S) 链接在普通点击时会在该类型已注 ## 滚动归属 -Chat 会在历史前插与 renderer 重新挂载时恢复语义锚点。没有读者移动的贴底滚动事件会立即更新跟随归属,避免后续布局变化使其底部位置失效。读者移动即使位于跟随阈值内,也保持待处理直到采样周期或 `scrollend`,防止布局增长抵消小幅滚动操作。提交正文输入或 steering 时立即恢复跟随底部,并清除先前待处理的读者滚动采样。读者跟随底部时,`ResizeObserver` 追随新的底部,并且无需读取行几何就选中最后一个已加载轮次;读者离开底部后,高度变化会保持顶部位置,再由阅读线几何选择活跃轮次。轮次导航预览位于 Markdown 代码块粘性头栏上方,而导航外框始终处于 composer 上方的 transcript 区域内。 +Chat 会在历史前插与 renderer 重新挂载时恢复语义锚点,并且只在跟随底部时禁用自己滚动区域的浏览器自动锚定。没有读者移动的贴底滚动事件,以及确实到达最底部的读者输入,会立即更新跟随归属,避免后续布局变化使其底部位置失效。其他读者移动即使位于跟随阈值内,也保持待处理直到采样周期或 `scrollend`,防止布局增长抵消小幅滚动操作。提交正文输入或 steering 时立即恢复跟随底部,并清除先前待处理的读者滚动采样。读者跟随底部时,`ResizeObserver` 追随新的底部,并且无需读取行几何就选中最后一个已加载轮次;读者离开底部后,高度变化会保持顶部位置,再由阅读线几何选择活跃轮次。轮次导航预览位于 Markdown 代码块粘性头栏上方,而导航外框始终处于 composer 上方的 transcript 区域内。 轮次轨道只挂载可见刻度、预加载范围及键盘焦点刻度的相邻项。固定间距和观察到的视口尺寸决定滚动偏移,不读取 DOM 滚动总高度。初始定位等待正文恢复活跃轮次,以及轨道首次获得可用视口尺寸。ref 控制接口分别支持激活轮次和仅滚动轨道;正文自身仍完整挂载。 diff --git a/packages/client/ui-chat/src/client/chat/ChatView.module.css b/packages/client/ui-chat/src/client/chat/ChatView.module.css index 0b1487cefb..298271f364 100644 --- a/packages/client/ui-chat/src/client/chat/ChatView.module.css +++ b/packages/client/ui-chat/src/client/chat/ChatView.module.css @@ -20,6 +20,11 @@ container-type: inline-size; } +.root[data-chat-following-tail] .scroll, +:global([data-conversation-scroll]):has(.root[data-chat-following-tail]) { + overflow-anchor: none; +} + :global([data-conversation-scroll]) .root { flex: 0 0 auto; min-height: auto; diff --git a/packages/client/ui-chat/src/client/chat/ChatView.tsx b/packages/client/ui-chat/src/client/chat/ChatView.tsx index 83facf3576..257dad64ab 100644 --- a/packages/client/ui-chat/src/client/chat/ChatView.tsx +++ b/packages/client/ui-chat/src/client/chat/ChatView.tsx @@ -207,7 +207,7 @@ export function ChatView({ }) return ( -
+
{scroll.initialized && ( { - if (this.state.followingTail && !scroll.movedByReader) { + if ((!scroll.movedByReader && this.state.followingTail) + || (scroll.movedByReader && scroll.metrics.top >= scroll.metrics.floor)) { this.followTail() - this.sampled?.({ position: null, movedByReader: false, followingTail: true }) + this.sampled?.({ position: null, movedByReader: scroll.movedByReader, followingTail: true }) return } this.sampleTimer ??= window.setTimeout(this.flushSample, SCROLL_SAMPLE_INTERVAL_MS) 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 a25692a2d5..9db032dc27 100644 --- a/packages/client/ui-chat/tests/chat-view.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-view.client.spec.tsx @@ -2428,6 +2428,7 @@ describe('ChatView', () => { readerScroll(scroller, 100) // far from bottom const backButton = view.getByLabelText('回到底部') expect(backButton).toBeTruthy() + expect(view.container.querySelector('[data-chat-following-tail]')).toBeNull() // Streaming growth must NOT drag a scrolled-away reader down. act(() => { h.setChat({ partial: { turn: 1, step: 1, blocks: [{ kind: 'text', text: 'grow' }] } }) @@ -2435,6 +2436,7 @@ describe('ChatView', () => { expect(scroller.scrollTop).toBe(100) fireEvent.click(backButton) expect(scroller.scrollTop).toBe(700) + expect(view.container.querySelector('[data-chat-following-tail]')).not.toBeNull() // At the bottom again: follow re-arms and the button unmounts. expect(view.queryByLabelText('回到底部')).toBeNull() }) @@ -2553,6 +2555,25 @@ describe('ChatView', () => { expect(scroller.scrollTop).toBe(680) }) + it('keeps following when reader input reaches the floor before growth and scrollend', () => { + const h = makeHarness({ nodes: [user(1, 'q'), assistant(2, 'a')] }) + const view = render() + const scroller = view.container.querySelector('[class*="scroll"]') as HTMLDivElement + const metrics = installScrollMetrics(scroller, 1_000, 300) + readerScroll(scroller, 100) + expect(view.getByLabelText('回到底部')).toBeTruthy() + + scroller.scrollTop = 700 + fireEvent.scroll(scroller) + metrics.setHeight(1_030) + act(() => { h.setSession({ running: true }) }) + fireEvent(scroller, new Event('scrollend')) + + expect(scroller.scrollTop).toBe(730) + expect(view.queryByLabelText('回到底部')).toBeNull() + expect(h.chatScroll.read()).toBeNull() + }) + it('follows a new submission immediately while an earlier scroll sample is pending', () => { const nodes = [user(1, 'q'), assistant(2, 'a')] const h = makeHarness({ nodes })