fix(chat): keep long streaming timelines at the latest output

This commit is contained in:
Sycun committed 2026-11-13 08:50:23 +08:00
1 parent 335c985516
commit 18b4f82400
6 files changed
+223 -25

No files matched your search

+147
View File
@@ -0,0 +1,147 @@
/* Offline regression. Requires Playwright and Chrome (or CHROME_PATH).
* Run: node --test scripts/chat-scroll-browser.test.cjs
*/
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { test } = require('node:test');
const { chromium } = require('playwright');
const read = file => fs.readFileSync(path.join(__dirname, '..', 'web/static', file), 'utf8');
async function scrollState(page) {
return page.evaluate(() => {
const chat = document.getElementById('chat-messages');
const timeline = document.querySelector('.progress-timeline');
return {
outerGap: chat.scrollHeight - chat.clientHeight - chat.scrollTop,
innerGap: timeline.scrollHeight - timeline.clientHeight - timeline.scrollTop,
innerTop: timeline.scrollTop,
outerFollowing: window.captureScrollPinState(),
pruned: !!timeline.querySelector('.timeline-live-pruned-marker')
};
});
}
test('long live and restored conversations stay at the latest iteration without stealing manual scroll', async () => {
const browser = await chromium.launch({
...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}),
});
try {
for (const width of [1440, 390]) {
for (const restored of [false, true]) {
const label = `${width}px ${restored ? 'restored' : 'live'}`;
const page = await browser.newPage({ viewport: { width, height: 820 } });
try {
await page.route('**/*', route => route.request().url() === 'http://chat.test/'
? route.fulfill({
contentType: 'text/html',
body: `<!doctype html><html data-theme="dark"><body>
<div class="chat-container" style="height: 700px">
<div id="chat-messages" class="chat-messages"></div>
<button id="chat-return-latest" hidden></button>
</div></body></html>`
})
: route.abort());
await page.goto('http://chat.test/');
for (const file of ['style.css', 'mobile.css']) {
await page.addStyleTag({ content: read('css/' + file) });
}
// Supply only the chat globals required by the real progress renderer.
await page.addScriptTag({ content: `
let messageCounter = 0, currentConversationId = '';
const escapeHtml = text => escapeHtmlLocal(text);
` });
for (const file of ['chat-scroll.js', 'monitor.js']) {
await page.addScriptTag({ content: read('js/' + file) });
}
await page.evaluate(async restored => {
const chat = document.getElementById('chat-messages');
for (let i = 0; i < 30; i++) {
const row = document.createElement('div');
row.className = 'message user';
row.innerHTML = '<div class="message-bubble">Synthetic history</div>';
chat.append(row);
}
if (restored) {
chat.insertAdjacentHTML('beforeend', `
<div class="message assistant assistant-turn-with-process">
<div class="message-content">
<div id="process-details-restored" class="process-details-container is-streaming">
<div class="process-details-content"><div class="progress-timeline expanded"></div></div>
</div>
</div>
</div>`);
startProcessDetailsLatestFollow('restored');
} else {
addProgressMessage();
}
const timeline = document.querySelector('.progress-timeline');
for (let i = 0; i < (restored ? 50 : 156); i++) {
addTimelineItem(timeline, 'reasoning_chain', {
title: 'Synthetic reasoning ' + i,
message: 'Example reasoning text.\n'.repeat(i % 11 === 0 ? 65 : i % 9 + 1)
});
if (i % 10 === 0) await new Promise(requestAnimationFrame);
}
}, restored);
await page.waitForFunction(() => {
const tl = document.querySelector('.progress-timeline');
const chat = document.getElementById('chat-messages');
return tl.scrollHeight - tl.clientHeight - tl.scrollTop <= 2 &&
chat.scrollHeight - chat.clientHeight - chat.scrollTop <= 2;
}, null, { timeout: 2000 });
const latest = await scrollState(page);
assert.equal(latest.pruned, !restored, label);
const box = await page.locator('.progress-timeline').boundingBox();
await page.mouse.move(box.x + 40, box.y + box.height / 2);
await page.mouse.wheel(0, -420);
await page.waitForFunction(() => processDetailsDistanceFromLatest(
document.querySelector('.progress-timeline')) > 100);
const reading = await scrollState(page);
assert.equal(reading.outerFollowing, true, label);
assert.ok(reading.outerGap <= 2, label);
if (restored) {
// Upgrading the restore follower to the live subscription preserves reading position.
await page.evaluate(() => startProcessDetailsLatestFollow('restored', { persistent: true }));
}
await page.evaluate(async () => {
const row = document.querySelector('.progress-timeline .timeline-item:last-child .timeline-item-content');
scheduleStreamPlainTextUpdate(row, row.textContent + 'A new line.\n'.repeat(20));
await new Promise(requestAnimationFrame);
await new Promise(requestAnimationFrame);
await new Promise(requestAnimationFrame);
});
const afterUpdate = await scrollState(page);
assert.equal(afterUpdate.innerTop, reading.innerTop, label);
assert.ok(afterUpdate.innerGap > reading.innerGap, label);
if (restored) {
await page.locator('.process-details-return-latest').click();
} else {
await page.mouse.wheel(0, 100000);
}
await page.waitForFunction(() => processDetailsDistanceFromLatest(
document.querySelector('.progress-timeline')) <= 2);
await page.evaluate(async () => {
const timeline = document.querySelector('.progress-timeline');
addTimelineItem(timeline, 'reasoning_chain', {
title: 'Latest iteration', message: 'More output.\n'.repeat(50)
});
await new Promise(requestAnimationFrame);
await new Promise(requestAnimationFrame);
await new Promise(requestAnimationFrame);
});
const atBottom = await scrollState(page);
assert.ok(atBottom.innerGap <= 2 && atBottom.outerGap <= 2, label);
} finally {
await page.close();
}
}
}
} finally {
await browser.close();
}
});
+11
View File
@@ -3514,6 +3514,12 @@ html[data-theme="dark"] .sidebar-content:hover::-webkit-scrollbar-thumb:hover {
scrollbar-color: color-mix(in srgb, var(--text-muted) 55%, transparent) transparent;
}
/* 贴底时由滚动控制器定位;浏览历史时保留浏览器的锚定。 */
#chat-messages.is-following-latest,
#chat-messages .progress-timeline.is-following-latest {
overflow-anchor: none;
}
.chat-messages::-webkit-scrollbar {
width: 4px;
height: 4px;
@@ -7958,6 +7964,11 @@ html[data-theme="dark"] .login-card .login-submit:disabled {
contain-intrinsic-size: auto 72px;
}
/* 跟随中的时间线使用实际高度,避免滚到底后才展开估算高度并把最新内容推出视口。 */
#chat-messages .progress-timeline.has-latest-follow > .timeline-item {
content-visibility: visible;
}
.timeline-live-pruned-marker {
position: sticky;
top: 0;
+1 -1
View File
@@ -283,7 +283,7 @@ test('刷新后迭代思考区独立跟随最新内容且允许用户上滑解
assert.match(returnLatestSource, /window\.ensureProcessDetailsReturnLatestControl = ensureProcessDetailsReturnLatestControl/);
assert.match(startSource, /new MutationObserver\(scheduleFollowLatest\)/);
assert.match(startSource, /characterData: true/);
assert.match(startSource, /new ResizeObserver\(scheduleFollowLatest\)/);
assert.match(startSource, /new ResizeObserver\(function \(\) \{\s*scheduleFollowLatest\(\)/);
assert.match(startSource, /ensureProcessDetailsReturnLatestControl\(timeline\)/);
assert.match(startSource, /markProcessDetailsReturnLatestPending\(timeline\)/);
assert.match(startSource, /timeline\.scrollTo\(\{ top: timeline\.scrollHeight, behavior: 'instant' \}\)/);
+30 -9
View File
@@ -387,6 +387,7 @@
function setScrollFollowing() {
scrollMode = 'following';
getChatMessagesEl()?.classList.add('is-following-latest');
detachLockUntil = 0;
userScrollIntentUntil = 0;
hasPendingNewBelow = false;
@@ -401,8 +402,10 @@
function setScrollDetached() {
scrollMode = 'detached';
getChatMessagesEl()?.classList.remove('is-following-latest');
detachLockUntil = Date.now() + DETACH_LOCK_MS;
cancelAnimationFrame(scrollFollowRaf);
scrollFollowRaf = 0;
scrollSettleGeneration += 1;
conversationRestoreGeneration += 1;
if (isStreamActive()) {
@@ -468,8 +471,11 @@
markPendingNewBelow();
return;
}
cancelAnimationFrame(scrollFollowRaf);
scrollFollowRaf = requestAnimationFrame(scrollChatToBottomInstant);
if (scrollFollowRaf) return;
scrollFollowRaf = requestAnimationFrame(function () {
scrollFollowRaf = 0;
scrollChatToBottomInstant();
});
}
/**
@@ -551,6 +557,7 @@
function forceScrollChatToBottom() {
cancelAnimationFrame(scrollFollowRaf);
scrollFollowRaf = 0;
setScrollFollowing();
scrollChatToBottomInstant();
updateTurnRailState();
@@ -665,14 +672,25 @@
updateTurnRailState();
}
function nestedTimelineCanScroll(target, direction) {
const timeline = target?.closest?.('.progress-timeline.expanded');
if (!timeline || scrollRange(timeline) <= CHAT_SCROLL_FOLLOW_RESUME_THRESHOLD_PX) return false;
return direction < 0
? timeline.scrollTop > CHAT_SCROLL_FOLLOW_RESUME_THRESHOLD_PX
: distanceFromBottom(timeline) > CHAT_SCROLL_FOLLOW_RESUME_THRESHOLD_PX;
}
function bindChatScrollListeners() {
if (listenersBound) return;
const el = getChatMessagesEl();
if (!el) return;
listenersBound = true;
el.classList.toggle('is-following-latest', scrollMode === 'following');
rememberScrollPosition(el);
el.addEventListener('wheel', function (e) {
// 只有内层到达边界后,滚轮才会传给外层对话区。
if (nestedTimelineCanScroll(e.target, e.deltaY)) return;
if (Math.abs(e.deltaY) > 1) {
userScrollIntentUntil = Date.now() + 1200;
}
@@ -691,22 +709,25 @@
el.addEventListener('keydown', function (e) {
const scrollKeys = ['ArrowUp', 'PageUp', 'Home', 'ArrowDown', 'PageDown', 'End', ' '];
if (scrollKeys.includes(e.key)) {
userScrollIntentUntil = Date.now() + 1200;
}
if (e.key === 'ArrowUp' || e.key === 'PageUp' || e.key === 'Home' || (e.key === ' ' && e.shiftKey)) {
if (e.defaultPrevented || !scrollKeys.includes(e.key)) return;
const upwards = e.key === 'ArrowUp' || e.key === 'PageUp' || e.key === 'Home' || (e.key === ' ' && e.shiftKey);
if (nestedTimelineCanScroll(e.target, upwards ? -1 : 1)) return;
userScrollIntentUntil = Date.now() + 1200;
if (upwards) {
setScrollDetached();
}
});
el.addEventListener('touchmove', function (e) {
if (e.touches && e.touches.length === 1) {
const y = e.touches[0].clientY;
const delta = (el._csTouchLastY ?? y) - y;
el._csTouchLastY = y;
if (nestedTimelineCanScroll(e.target, delta)) return;
userScrollIntentUntil = Date.now() + 1200;
el._csTouchLastY = el._csTouchLastY != null ? el._csTouchLastY : e.touches[0].clientY;
if (e.touches[0].clientY > el._csTouchLastY + 4) {
if (delta < -4) {
setScrollDetached();
}
el._csTouchLastY = e.touches[0].clientY;
}
}, { passive: true });
el.addEventListener('touchstart', function (e) {
+31 -12
View File
@@ -1878,6 +1878,7 @@ function syncProcessDetailsLatestFollowAfterManualReturn(timeline) {
processDetailsLatestFollowStates.forEach(function (state) {
if (!state || state.timeline !== timeline) return;
state.detached = false;
timeline.classList.add('is-following-latest');
state.hasPendingNewBelow = false;
state.userScrollIntentUntil = 0;
state.lastScrollTop = timeline.scrollTop;
@@ -2124,6 +2125,7 @@ function stopProcessDetailsLatestFollow(assistantMessageId) {
const state = processDetailsLatestFollowStates.get(key);
if (!state) return false;
state.stopped = true;
state.timeline.classList.remove('has-latest-follow', 'is-following-latest');
if (state.rafId) cancelAnimationFrame(state.rafId);
if (state.timeoutId) clearTimeout(state.timeoutId);
if (state.observer) state.observer.disconnect();
@@ -2155,16 +2157,22 @@ function startProcessDetailsLatestFollow(assistantMessageId, options) {
const timeline = explicitTimeline || (container && container.querySelector('.progress-timeline'));
if (!container || !timeline) return false;
const persistent = !!opts.persistent;
const previousState = processDetailsLatestFollowStates.get(key);
// 最新页恢复接入补流时保留原状态,避免把正在阅读历史的用户拉到底部。
if (previousState && previousState.timeline === timeline && persistent) {
clearTimeout(previousState.timeoutId);
previousState.timeoutId = 0;
return true;
}
stopProcessDetailsLatestFollow(key);
ensureProcessDetailsReturnLatestControl(timeline);
const persistent = !!opts.persistent;
const durationMs = Number.isFinite(Number(opts.durationMs))
? Math.max(250, Number(opts.durationMs))
: PROCESS_DETAILS_RESTORE_FOLLOW_MS;
const state = {
stopped: false,
detached: false,
persistent: persistent,
timeline: timeline,
hasPendingNewBelow: false,
lastScrollTop: timeline.scrollTop,
@@ -2178,9 +2186,11 @@ function startProcessDetailsLatestFollow(assistantMessageId, options) {
cleanup: []
};
processDetailsLatestFollowStates.set(key, state);
timeline.classList.add('has-latest-follow', 'is-following-latest');
const detachForUserNavigation = function () {
state.detached = true;
timeline.classList.remove('is-following-latest');
if (state.rafId) {
cancelAnimationFrame(state.rafId);
state.rafId = 0;
@@ -2192,7 +2202,12 @@ function startProcessDetailsLatestFollow(assistantMessageId, options) {
if (Math.abs(event.deltaY) > 1) {
state.userScrollIntentUntil = Date.now() + 1200;
}
if (event.deltaY < -1) detachForUserNavigation();
if (event.deltaY < -1 && timeline.scrollTop > PROCESS_DETAILS_FOLLOW_RESUME_THRESHOLD_PX) {
detachForUserNavigation();
} else if (event.deltaY > 1 && state.detached &&
processDetailsDistanceFromLatest(timeline) <= PROCESS_DETAILS_FOLLOW_RESUME_THRESHOLD_PX) {
syncProcessDetailsLatestFollowAfterManualReturn(timeline);
}
};
const onPointerDown = function (event) {
if (!event) return;
@@ -2202,11 +2217,12 @@ function startProcessDetailsLatestFollow(assistantMessageId, options) {
}
};
const onKeyDown = function (event) {
if (!event) return;
if (!event || event.defaultPrevented) return;
if (['ArrowUp', 'PageUp', 'Home', 'ArrowDown', 'PageDown', 'End', ' '].includes(event.key)) {
state.userScrollIntentUntil = Date.now() + 1200;
}
if (event.key === 'ArrowUp' || event.key === 'PageUp' || event.key === 'Home') {
if ((event.key === 'ArrowUp' || event.key === 'PageUp' || event.key === 'Home' ||
(event.key === ' ' && event.shiftKey)) && timeline.scrollTop > PROCESS_DETAILS_FOLLOW_RESUME_THRESHOLD_PX) {
detachForUserNavigation();
}
};
@@ -2219,7 +2235,8 @@ function startProcessDetailsLatestFollow(assistantMessageId, options) {
if (!event || !event.touches || event.touches.length !== 1) return;
const nextY = event.touches[0].clientY;
state.userScrollIntentUntil = Date.now() + 1200;
if (state.touchLastY != null && nextY > state.touchLastY + 4) {
if (state.touchLastY != null && nextY > state.touchLastY + 4 &&
timeline.scrollTop > PROCESS_DETAILS_FOLLOW_RESUME_THRESHOLD_PX) {
detachForUserNavigation();
}
state.touchLastY = nextY;
@@ -2248,6 +2265,7 @@ function startProcessDetailsLatestFollow(assistantMessageId, options) {
distance <= PROCESS_DETAILS_FOLLOW_RESUME_THRESHOLD_PX
) {
state.detached = false;
timeline.classList.add('is-following-latest');
state.hasPendingNewBelow = false;
scheduleFollowLatest();
}
@@ -2285,11 +2303,6 @@ function startProcessDetailsLatestFollow(assistantMessageId, options) {
state.lastScrollTop = timeline.scrollTop;
state.lastScrollRange = Math.max(0, timeline.scrollHeight - timeline.clientHeight);
updateProcessDetailsReturnLatestControl(timeline);
// 内层迭代区与外层对话区分别粘底;用户上滑内层后,本状态会暂停两者的自动跟随。
if (window.CyberStrikeChatScroll &&
typeof window.CyberStrikeChatScroll.scrollIfPinned === 'function') {
window.CyberStrikeChatScroll.scrollIfPinned(true);
}
};
const scheduleFollowLatest = function () {
if (state.stopped || state.rafId) return;
@@ -2305,7 +2318,13 @@ function startProcessDetailsLatestFollow(assistantMessageId, options) {
state.observer = new MutationObserver(scheduleFollowLatest);
state.observer.observe(timeline, { childList: true, subtree: true, characterData: true });
if (typeof ResizeObserver === 'function') {
state.resizeObserver = new ResizeObserver(scheduleFollowLatest);
state.resizeObserver = new ResizeObserver(function () {
scheduleFollowLatest();
// 展开、收起和尺寸过渡会改变外层对话高度,且可能没有新增 DOM。
if (timeline.closest('#chat-messages')) {
window.CyberStrikeChatScroll?.scrollIfPinned(true);
}
});
state.resizeObserver.observe(timeline);
}
scheduleFollowLatest();
+3 -3
View File
@@ -39,7 +39,7 @@
}
})();
</script>
<link rel="stylesheet" href="/static/css/style.css?v=20261112-related-facts-theme">
<link rel="stylesheet" href="/static/css/style.css?v=20261113-chat-scroll">
<link rel="stylesheet" href="/static/css/vulnerability-download.css?v=20261030-2">
<link rel="stylesheet" href="/static/css/tool-guard.css?v=20260907-7">
<link rel="stylesheet" href="/static/css/chat-plan-progress.css?v=20260813-4">
@@ -7068,8 +7068,8 @@
<script src="/static/js/assets.js?v=20260717-7"></script>
<script src="/static/js/agents.js"></script>
<script src="/static/js/dashboard.js?v=20261011-token-settings-cache-only"></script>
<script src="/static/js/chat-scroll.js?v=20261112-chat-scroll"></script>
<script src="/static/js/monitor.js?v=20261011-token-usage-pagination-20261027-tool-title-20261112-chat-scroll"></script>
<script src="/static/js/chat-scroll.js?v=20261113-chat-scroll"></script>
<script src="/static/js/monitor.js?v=20261011-token-usage-pagination-20261027-tool-title-20261113-chat-scroll"></script>
<script src="/static/js/attack-chain-context.js?v=20261012-summary-2"></script>
<script src="/static/js/chat.js?v=20261016-context-memory-token-usage-pagination-20261027-tool-title-20261112-chat-scroll"></script>
<script src="/static/js/chat-plan-progress.js?v=20260815-1"></script>