diff --git a/scripts/chat-scroll-browser.test.cjs b/scripts/chat-scroll-browser.test.cjs
new file mode 100644
index 00000000..7750295a
--- /dev/null
+++ b/scripts/chat-scroll-browser.test.cjs
@@ -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: `
+ `
+ })
+ : 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 = 'Synthetic history
';
+ chat.append(row);
+ }
+ if (restored) {
+ chat.insertAdjacentHTML('beforeend', `
+ `);
+ 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();
+ }
+});
diff --git a/web/static/css/style.css b/web/static/css/style.css
index 59e09e1d..4be481be 100644
--- a/web/static/css/style.css
+++ b/web/static/css/style.css
@@ -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;
diff --git a/web/static/js/chat-scroll-refresh.test.cjs b/web/static/js/chat-scroll-refresh.test.cjs
index fab6cb2c..75c5f778 100644
--- a/web/static/js/chat-scroll-refresh.test.cjs
+++ b/web/static/js/chat-scroll-refresh.test.cjs
@@ -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' \}\)/);
diff --git a/web/static/js/chat-scroll.js b/web/static/js/chat-scroll.js
index b969e050..9696c6be 100644
--- a/web/static/js/chat-scroll.js
+++ b/web/static/js/chat-scroll.js
@@ -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) {
diff --git a/web/static/js/monitor.js b/web/static/js/monitor.js
index fc8264f5..33c5888a 100644
--- a/web/static/js/monitor.js
+++ b/web/static/js/monitor.js
@@ -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();
diff --git a/web/templates/index.html b/web/templates/index.html
index b5f6ba98..90463a3a 100644
--- a/web/templates/index.html
+++ b/web/templates/index.html
@@ -39,7 +39,7 @@
}
})();
-
+
@@ -7068,8 +7068,8 @@
-
-
+
+