From ebde89af1eb9a3c0a3ff7b15d27e88d259e90f78 Mon Sep 17 00:00:00 2001 From: allenliang2022 Date: Fri, 26 Jun 2026 11:46:12 +0800 Subject: [PATCH 1/6] fix(chat): suppress post-render scroll artifacts --- static/ui.js | 12 +++++++++++ ...est_issue4856_android_scroll_regression.py | 20 +++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/static/ui.js b/static/ui.js index 2537863013a..c8099f1b12b 100644 --- a/static/ui.js +++ b/static/ui.js @@ -3732,6 +3732,10 @@ let _lastMessageTouchScrollIntentMs=-Infinity; let _deferredOlderMessagesTimer=0; const MESSAGE_TOUCH_SCROLL_SUPPRESS_MS=1200; let _newMessageCueVisible=false; +let _lastMessageRenderAt=-Infinity; +function _recentMessageRenderArtifactWindow(ms){ + return performance.now()-_lastMessageRenderAt<(ms||1400); +} function _cancelBottomSettle(){ _bottomSettleToken++; if(_settleRO){ _settleRO.disconnect(); _settleRO=null; } clearTimeout(_settleTimer); clearTimeout(_settleFinalTimer); cancelAnimationFrame(_settleRAF); } function _markMessageTouchScrollIntent(active=true){ _messageTouchScrollActive=!!active; @@ -3981,6 +3985,13 @@ if(typeof window!=='undefined'){ _lastMessageClientHeight=el.clientHeight; const movedUp=!grew&&_lastScrollTop!==null&&top<_lastScrollTop-2; const movedDown=_lastScrollTop!==null&&top>_lastScrollTop+2; + if(movedUp + && !_recentMessageTouchScrollIntent() + && !_recentNonMessageScrollIntent() + && _recentMessageRenderArtifactWindow(1400)){ + _lastScrollTop=top; + return; + } _lastScrollTop=top; if(movedUp){ _cancelBottomSettle(); @@ -11285,6 +11296,7 @@ function _maybeRecoverVirtualizedBlankViewport(options, preserveScroll, virtualW } function renderMessages(options){ + _lastMessageRenderAt=performance.now(); const preserveScroll=!!(options&&options.preserveScroll); const virtualFallback=!!(options&&options._virtualFallback); // Capture the pre-wipe scroll position when preserving OR when the reader has diff --git a/tests/test_issue4856_android_scroll_regression.py b/tests/test_issue4856_android_scroll_regression.py index a1c3f60af85..f819ea06631 100644 --- a/tests/test_issue4856_android_scroll_regression.py +++ b/tests/test_issue4856_android_scroll_regression.py @@ -104,6 +104,26 @@ def test_rebuild_path_marks_dom_wipe_scroll_as_programmatic(): ) +def test_recent_render_scroll_artifact_window_suppresses_upward_unpin(): + # Some browsers emit a follow-up scroll event shortly after renderMessages() + # finishes (for example while late layout settles after a send). With no + # wheel/touch intent, that post-render upward delta is still a render + # artifact and must not disable live follow. + assert "let _lastMessageRenderAt=-Infinity" in UI_JS + assert "_lastMessageRenderAt=performance.now()" in UI_JS + assert "function _recentMessageRenderArtifactWindow" in UI_JS + listener_idx = UI_JS.find("el.addEventListener('scroll'") + assert listener_idx != -1, "messages scroll listener not found" + listener = UI_JS[listener_idx: listener_idx + 2500] + assert "_recentMessageRenderArtifactWindow(1400)" in listener + assert "!_recentMessageTouchScrollIntent()" in listener + assert "!_recentNonMessageScrollIntent()" in listener + assert listener.find("return;") < listener.find("if(movedUp){"), ( + "recent render artifact scrolls must return before the movedUp branch " + "can mark the reader unpinned." + ) + + def test_streaming_tick_calls_fix_before_dom_writes(): # The streaming render tick in messages.js must call _fixMobileScrollJank() # before _lastRenderMs=performance.now() so anchor suppression covers every From 7b262954f147ff1d1cc18084773f53d5317d860c Mon Sep 17 00:00:00 2001 From: allenliang2022 Date: Fri, 26 Jun 2026 12:43:23 +0800 Subject: [PATCH 2/6] fix(chat): guard post-render artifact suppression so #4295 harness passes The new movedUp suppression branch called _recentMessageRenderArtifactWindow() and the intent helpers in an unguarded position. The #4295 unit harness injects the scroll-listener body via new Function() without those helpers, so the branch threw ReferenceError on a movedUp sample and crashed the node subprocess. Reorder the && chain with typeof-function guards first; production evaluates the real helpers, the harness short-circuits before any call. Behavior unchanged. --- static/ui.js | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/static/ui.js b/static/ui.js index c8099f1b12b..8685816736c 100644 --- a/static/ui.js +++ b/static/ui.js @@ -3985,10 +3985,18 @@ if(typeof window!=='undefined'){ _lastMessageClientHeight=el.clientHeight; const movedUp=!grew&&_lastScrollTop!==null&&top<_lastScrollTop-2; const movedDown=_lastScrollTop!==null&&top>_lastScrollTop+2; + // Suppress the post-render scroll artifact: right after renderMessages() + // rebuilds #msgInner, the browser can emit a non-user upward scroll event. + // The typeof guards keep this branch inert in unit harnesses that inject + // the listener body without these helpers (and short-circuit before any + // call), while production evaluates the real intent/recency helpers. if(movedUp + && typeof _recentMessageRenderArtifactWindow==='function' + && typeof _recentMessageTouchScrollIntent==='function' + && typeof _recentNonMessageScrollIntent==='function' + && _recentMessageRenderArtifactWindow(1400) && !_recentMessageTouchScrollIntent() - && !_recentNonMessageScrollIntent() - && _recentMessageRenderArtifactWindow(1400)){ + && !_recentNonMessageScrollIntent()){ _lastScrollTop=top; return; } From 70cc4b5add47fbc49e5bc08504156eba97a1ee89 Mon Sep 17 00:00:00 2001 From: allenliang2022 Date: Fri, 26 Jun 2026 16:17:36 +0800 Subject: [PATCH 3/6] fix(chat): scope post-render suppression to true no-intent artifacts (#4970 review) Maintainer dual-gate (Codex) found the suppression could swallow a genuine low-delta trackpad wheel scroll-up for ~1.4s after a render: _recordNonMessageScrollIntent() only recorded message-pane wheel intent at deltaY<-30, so a gentle deltaY:-5 left both intent helpers false and the post-render branch returned before movedUp set _messageUserUnpinned. - Track recent low-delta upward message-pane wheel intent separately (_lastMessageWheelIntentMs / _recentMessageWheelIntent), recorded for any upward wheel (deltaY<0). The decisive deltaY<-30 sticky-unpin is unchanged. - Require !_recentMessageWheelIntent() before suppressing the artifact, so a real gentle scroll-up inside the window still unpins. - Add behavioral node-harness regressions: gentle wheel inside the window unpins; no-intent artifact inside the window stays suppressed; outside the window unpins. Plus a source lock that low-delta intent is tracked. --- static/ui.js | 31 ++- ...est_issue4856_android_scroll_regression.py | 200 +++++++++++++++++- 2 files changed, 227 insertions(+), 4 deletions(-) diff --git a/static/ui.js b/static/ui.js index 8685816736c..b12f6d6afd1 100644 --- a/static/ui.js +++ b/static/ui.js @@ -3731,6 +3731,12 @@ let _messageTouchScrollActive=false; let _lastMessageTouchScrollIntentMs=-Infinity; let _deferredOlderMessagesTimer=0; const MESSAGE_TOUCH_SCROLL_SUPPRESS_MS=1200; +// #4970: track recent LOW-DELTA upward message-pane wheel intent separately from +// the decisive deltaY<-30 sticky-unpin threshold. A gentle trackpad wheel +// (deltaY:-5) is real user intent but never crosses -30, so without this the +// post-render artifact suppression would swallow it for the whole window. +const MESSAGE_WHEEL_INTENT_SUPPRESS_MS=1200; +let _lastMessageWheelIntentMs=-Infinity; let _newMessageCueVisible=false; let _lastMessageRenderAt=-Infinity; function _recentMessageRenderArtifactWindow(ms){ @@ -3744,6 +3750,13 @@ function _markMessageTouchScrollIntent(active=true){ function _recentMessageTouchScrollIntent(){ return _messageTouchScrollActive || performance.now()-_lastMessageTouchScrollIntentMs-30) right after a render still unpins + // instead of being swallowed for the artifact window. if(movedUp && typeof _recentMessageRenderArtifactWindow==='function' && typeof _recentMessageTouchScrollIntent==='function' && typeof _recentNonMessageScrollIntent==='function' + && typeof _recentMessageWheelIntent==='function' && _recentMessageRenderArtifactWindow(1400) && !_recentMessageTouchScrollIntent() - && !_recentNonMessageScrollIntent()){ + && !_recentNonMessageScrollIntent() + && !_recentMessageWheelIntent()){ _lastScrollTop=top; return; } diff --git a/tests/test_issue4856_android_scroll_regression.py b/tests/test_issue4856_android_scroll_regression.py index f819ea06631..9f191cb2ebc 100644 --- a/tests/test_issue4856_android_scroll_regression.py +++ b/tests/test_issue4856_android_scroll_regression.py @@ -114,16 +114,214 @@ def test_recent_render_scroll_artifact_window_suppresses_upward_unpin(): assert "function _recentMessageRenderArtifactWindow" in UI_JS listener_idx = UI_JS.find("el.addEventListener('scroll'") assert listener_idx != -1, "messages scroll listener not found" - listener = UI_JS[listener_idx: listener_idx + 2500] + listener = UI_JS[listener_idx: listener_idx + 4000] assert "_recentMessageRenderArtifactWindow(1400)" in listener assert "!_recentMessageTouchScrollIntent()" in listener assert "!_recentNonMessageScrollIntent()" in listener + assert "!_recentMessageWheelIntent()" in listener, ( + "#4970: the post-render artifact suppression must also require no recent " + "low-delta message-pane wheel intent so a gentle trackpad scroll-up is " + "not swallowed." + ) assert listener.find("return;") < listener.find("if(movedUp){"), ( "recent render artifact scrolls must return before the movedUp branch " "can mark the reader unpinned." ) +# ── #4970 low-delta wheel intent: behavioral node-harness ──────────────────── +import json # noqa: E402 +import shutil # noqa: E402 +import subprocess # noqa: E402 + +import pytest # noqa: E402 + +NODE = shutil.which("node") + + +def _balanced_block(src: str, brace_start: int) -> str: + depth = 0 + for i in range(brace_start, len(src)): + ch = src[i] + if ch == "{": + depth += 1 + elif ch == "}": + depth -= 1 + if depth == 0: + return src[brace_start + 1 : i] + raise AssertionError("balanced block not found") + + +def _scroll_listener_raf_body() -> str: + listener_start = UI_JS.index("el.addEventListener('scroll'") + raf_start = UI_JS.index("requestAnimationFrame(()=>", listener_start) + brace_start = UI_JS.index("{", raf_start) + return _balanced_block(UI_JS, brace_start) + + +def _run_listener_with_wheel_intent(samples, *, render_artifact, wheel_intent): + """Run the extracted scroll-listener body in node with controllable stubs. + + Mirrors the #4295 harness shape but injects the #4970 helpers so we can + exercise the production suppression path: artifact window active AND a + recent gentle wheel intent must still unpin (return _messageUserUnpinned). + """ + payload = { + "body": _scroll_listener_raf_body(), + "samples": samples, + "renderArtifact": bool(render_artifact), + "wheelIntent": bool(wheel_intent), + } + script = ( + "const payload = " + json.dumps(payload) + ";\n" + + r""" +const step = new Function( + 'el', + '_lastScrollTop', + '_lastMessageClientHeight', + '_nearBottomCount', + '_scrollPinned', + '_messageUserUnpinned', + '_newMessageCueVisible', + '_programmaticScroll', + '_cancelBottomSettle', + '_clearNewMessageScrollCue', + '_syncScrollToBottomCue', + '_updateSessionStartJumpButton', + '_isSessionEndlessScrollEnabled', + '_messagesTruncated', + '_loadOlderMessages', + '_recentMessageRenderArtifactWindow', + '_recentMessageTouchScrollIntent', + '_recentNonMessageScrollIntent', + '_recentMessageWheelIntent', + // The extracted listener body uses bare `return;` in the suppression branch. + // Wrap it in an inner arrow IIFE so that early return exits the IIFE (not the + // outer Function), then read the mutated locals afterward. Without this the + // suppression path would return undefined before the state snapshot. + '(()=>{' + payload.body + `})(); +return { + _lastScrollTop, + _lastMessageClientHeight, + _nearBottomCount, + _scrollPinned, + _messageUserUnpinned, +}; +` +); + +let state = { + _lastScrollTop: 800, + _lastMessageClientHeight: null, + _nearBottomCount: 0, + _scrollPinned: true, + _messageUserUnpinned: false, +}; + +const noop = () => {}; +const renderArtifact = () => payload.renderArtifact; +const noTouch = () => false; +const noNonMessage = () => false; +const wheelIntent = () => payload.wheelIntent; + +for (const sample of payload.samples) { + state = step( + sample, + state._lastScrollTop, + state._lastMessageClientHeight, + state._nearBottomCount, + state._scrollPinned, + state._messageUserUnpinned, + false, + false, + noop, + noop, + noop, + noop, + () => false, + false, + noop, + renderArtifact, + noTouch, + noNonMessage, + wheelIntent + ); +} + +console.log(JSON.stringify(state)); +""" + ) + result = subprocess.run( + [NODE, "-e", script], + check=True, + capture_output=True, + text=True, + timeout=30, + ) + return json.loads(result.stdout.strip()) + + +@pytest.mark.skipif(NODE is None, reason="node not on PATH") +class TestPostRenderWheelIntentScope: + # A small upward scrollTop delta (800 -> 760) is `movedUp`. We hold the + # render artifact window OPEN for all cases so the only variable is whether + # the reader had recent gentle wheel intent. + _SAMPLES = [{"scrollTop": 760, "scrollHeight": 1200, "clientHeight": 200}] + + def test_gentle_wheel_inside_artifact_window_still_unpins(self): + # #4970 MUST-FIX: with the artifact window active but a recent low-delta + # wheel intent, a real upward scroll must NOT be swallowed — it must + # unpin live-follow just like any genuine scroll-up. + state = _run_listener_with_wheel_intent( + self._SAMPLES, render_artifact=True, wheel_intent=True + ) + assert state["_messageUserUnpinned"] is True, ( + "A genuine gentle (low-delta) wheel scroll-up inside the post-render " + "artifact window must still unpin; the suppression must be scoped to " + "the no-intent artifact case only." + ) + assert state["_scrollPinned"] is False + + def test_no_intent_artifact_inside_window_is_suppressed(self): + # Control: same upward delta, same open window, but NO wheel intent — a + # true post-render artifact — stays pinned (the suppression still works). + state = _run_listener_with_wheel_intent( + self._SAMPLES, render_artifact=True, wheel_intent=False + ) + assert state["_messageUserUnpinned"] is False, ( + "A no-intent upward delta inside the artifact window is a render " + "artifact and must be suppressed (reader stays pinned)." + ) + assert state["_scrollPinned"] is True + + def test_gentle_wheel_outside_window_unpins(self): + # Outside the artifact window the suppression never applies, so the + # upward delta unpins regardless of intent tracking. + state = _run_listener_with_wheel_intent( + self._SAMPLES, render_artifact=False, wheel_intent=False + ) + assert state["_messageUserUnpinned"] is True + assert state["_scrollPinned"] is False + + +def test_low_delta_wheel_intent_is_tracked_separately(): + # The intent recorder must stamp _lastMessageWheelIntentMs for ANY upward + # wheel (deltaY<0), not only the decisive deltaY<-30 sticky-unpin threshold. + assert "let _lastMessageWheelIntentMs=-Infinity" in UI_JS + assert "function _recentMessageWheelIntent" in UI_JS + rec_idx = UI_JS.find("function _recordNonMessageScrollIntent") + assert rec_idx != -1, "_recordNonMessageScrollIntent not found" + rec = UI_JS[rec_idx: rec_idx + 1400] + assert "e.deltaY<0) _lastMessageWheelIntentMs=performance.now()" in rec, ( + "#4970: _recordNonMessageScrollIntent must record low-delta upward wheel " + "intent (deltaY<0) separately from the decisive deltaY<-30 unpin." + ) + # The decisive sticky-unpin threshold must remain unchanged. + assert "e.deltaY< -30" in rec, ( + "The existing deltaY<-30 direct sticky-unpin threshold must be preserved." + ) + + def test_streaming_tick_calls_fix_before_dom_writes(): # The streaming render tick in messages.js must call _fixMobileScrollJank() # before _lastRenderMs=performance.now() so anchor suppression covers every From 17cd7b07e7be02880241d9c2522f9868b0528564 Mon Sep 17 00:00:00 2001 From: allenliang2022 Date: Fri, 26 Jun 2026 18:06:23 +0800 Subject: [PATCH 4/6] fix(chat): reset wheel intent on session/stream resets + gate suppression on scrollbar drag (#4970 review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Maintainer dual-gate found two stale-state leaks in the new _lastMessageWheelIntentMs and one adjacent pre-existing gap; all three fixed: MUST-FIX 1 — _resetScrollDirectionTracker() (session switch) did not clear _lastMessageWheelIntentMs, so a gentle wheel in chat A left _recentMessageWheelIntent() true into chat B's first post-render window, under-suppressing the artifact and falsely unpinning. Now reset to -Infinity. MUST-FIX 2 — _resetStreamScrollFollow() (fresh stream) had the same leak: a gentle upward wheel within 1200ms of a new stream could silently disable live follow. Now reset to -Infinity. SHOULD-FIX 3 — the suppression branch ignored _scrollbarDragActive, so a manual scrollbar-drag upward scroll inside the 1400ms window was swallowed. Gate the branch on (typeof _scrollbarDragActive==='undefined' || !_scrollbarDragActive); typeof guard keeps the #4295 node harness inert. Tests: scrollbar-drag-inside-window-still-unpins behavioral regression (harness extended with injected _scrollbarDragActive), plus source locks for both resets and the scrollbar-drag gate. test_4856 + test_4295 green (17 passed), node --check clean. --- static/ui.js | 14 ++++ ...est_issue4856_android_scroll_regression.py | 76 ++++++++++++++++++- 2 files changed, 88 insertions(+), 2 deletions(-) diff --git a/static/ui.js b/static/ui.js index b12f6d6afd1..6851d290453 100644 --- a/static/ui.js +++ b/static/ui.js @@ -3878,6 +3878,11 @@ function _resetScrollDirectionTracker(){ _touchStartY=null; _messageTouchScrollActive=false; _lastMessageTouchScrollIntentMs=-Infinity; + // #4970 review: also clear low-delta wheel intent on session switch, else a + // gentle wheel in the previous chat leaves _recentMessageWheelIntent() true + // into the new chat's first post-render window — the artifact then isn't + // suppressed, falls into movedUp, and falsely unpins live-follow. + _lastMessageWheelIntentMs=-Infinity; clearTimeout(_deferredOlderMessagesTimer); _deferredOlderMessagesTimer=0; } @@ -3887,6 +3892,10 @@ function _resetStreamScrollFollow(){ _scrollPinned=true; _nearBottomCount=0; _lastScrollTop=null; + // #4970 review: clear low-delta wheel intent on fresh stream start too, else a + // gentle upward wheel within the prior 1200ms can under-suppress a genuine + // no-intent render artifact and silently disable live follow for the new stream. + _lastMessageWheelIntentMs=-Infinity; _cancelBottomSettle(); } if(typeof window!=='undefined'){ @@ -4013,11 +4022,16 @@ if(typeof window!=='undefined'){ // #4970: also require no recent low-delta message-pane wheel intent, so a // gentle trackpad scroll-up (deltaY>-30) right after a render still unpins // instead of being swallowed for the artifact window. + // #4970 review: and never suppress while a scrollbar drag is active — a + // manual scrollbar-drag upward scroll inside the window is real intent. + // typeof guard keeps the #4295 node harness (no _scrollbarDragActive + // injected) inert via short-circuit. if(movedUp && typeof _recentMessageRenderArtifactWindow==='function' && typeof _recentMessageTouchScrollIntent==='function' && typeof _recentNonMessageScrollIntent==='function' && typeof _recentMessageWheelIntent==='function' + && (typeof _scrollbarDragActive==='undefined' || !_scrollbarDragActive) && _recentMessageRenderArtifactWindow(1400) && !_recentMessageTouchScrollIntent() && !_recentNonMessageScrollIntent() diff --git a/tests/test_issue4856_android_scroll_regression.py b/tests/test_issue4856_android_scroll_regression.py index 9f191cb2ebc..90365d2fa25 100644 --- a/tests/test_issue4856_android_scroll_regression.py +++ b/tests/test_issue4856_android_scroll_regression.py @@ -159,7 +159,9 @@ def _scroll_listener_raf_body() -> str: return _balanced_block(UI_JS, brace_start) -def _run_listener_with_wheel_intent(samples, *, render_artifact, wheel_intent): +def _run_listener_with_wheel_intent( + samples, *, render_artifact, wheel_intent, scrollbar_drag=False +): """Run the extracted scroll-listener body in node with controllable stubs. Mirrors the #4295 harness shape but injects the #4970 helpers so we can @@ -171,6 +173,7 @@ def _run_listener_with_wheel_intent(samples, *, render_artifact, wheel_intent): "samples": samples, "renderArtifact": bool(render_artifact), "wheelIntent": bool(wheel_intent), + "scrollbarDrag": bool(scrollbar_drag), } script = ( "const payload = " + json.dumps(payload) + ";\n" @@ -195,6 +198,7 @@ def _run_listener_with_wheel_intent(samples, *, render_artifact, wheel_intent): '_recentMessageTouchScrollIntent', '_recentNonMessageScrollIntent', '_recentMessageWheelIntent', + '_scrollbarDragActive', // The extracted listener body uses bare `return;` in the suppression branch. // Wrap it in an inner arrow IIFE so that early return exits the IIFE (not the // outer Function), then read the mutated locals afterward. Without this the @@ -244,7 +248,8 @@ def _run_listener_with_wheel_intent(samples, *, render_artifact, wheel_intent): renderArtifact, noTouch, noNonMessage, - wheelIntent + wheelIntent, + payload.scrollbarDrag ); } @@ -303,6 +308,22 @@ def test_gentle_wheel_outside_window_unpins(self): assert state["_messageUserUnpinned"] is True assert state["_scrollPinned"] is False + def test_scrollbar_drag_inside_window_still_unpins(self): + # #4970 review SHOULD-FIX: a manual scrollbar-drag upward scroll inside + # the post-render window is real user intent and must NOT be swallowed, + # even with no wheel/touch intent recorded. + state = _run_listener_with_wheel_intent( + self._SAMPLES, + render_artifact=True, + wheel_intent=False, + scrollbar_drag=True, + ) + assert state["_messageUserUnpinned"] is True, ( + "A scrollbar-drag upward scroll inside the artifact window must " + "unpin; the suppression must not swallow an active scrollbar drag." + ) + assert state["_scrollPinned"] is False + def test_low_delta_wheel_intent_is_tracked_separately(): # The intent recorder must stamp _lastMessageWheelIntentMs for ANY upward @@ -322,6 +343,57 @@ def test_low_delta_wheel_intent_is_tracked_separately(): ) +def _extract_fn_body(name: str) -> str: + idx = UI_JS.find("function " + name + "(") + assert idx != -1, name + " not found in ui.js" + brace = UI_JS.index("{", idx) + depth = 0 + for i in range(brace, len(UI_JS)): + ch = UI_JS[i] + if ch == "{": + depth += 1 + elif ch == "}": + depth -= 1 + if depth == 0: + return UI_JS[idx : i + 1] + raise AssertionError("unbalanced body for " + name) + + +def test_session_switch_reset_clears_wheel_intent(): + # #4970 review MUST-FIX 1: _resetScrollDirectionTracker() must clear the + # low-delta wheel intent stamp so a gentle wheel in the previous chat does + # not leak into the new chat's first post-render artifact window. + body = _extract_fn_body("_resetScrollDirectionTracker") + assert "_lastMessageWheelIntentMs=-Infinity" in body, ( + "_resetScrollDirectionTracker() must reset _lastMessageWheelIntentMs so " + "stale wheel intent cannot cross a session switch." + ) + + +def test_stream_start_reset_clears_wheel_intent(): + # #4970 review MUST-FIX 2: _resetStreamScrollFollow() must clear the wheel + # intent stamp so a gentle wheel just before a fresh stream cannot + # under-suppress a no-intent artifact and silently disable live follow. + body = _extract_fn_body("_resetStreamScrollFollow") + assert "_lastMessageWheelIntentMs=-Infinity" in body, ( + "_resetStreamScrollFollow() must reset _lastMessageWheelIntentMs so " + "stale wheel intent cannot cross a fresh stream start." + ) + + +def test_suppression_gates_on_scrollbar_drag(): + # #4970 review SHOULD-FIX 3: the post-render suppression must not fire while + # a scrollbar drag is active — that upward scroll is real user intent. + assert "let _scrollbarDragActive=false" in UI_JS + listener_idx = UI_JS.find("el.addEventListener('scroll'") + assert listener_idx != -1, "messages scroll listener not found" + listener = UI_JS[listener_idx: listener_idx + 4000] + assert "!_scrollbarDragActive" in listener, ( + "#4970 review: the suppression branch must reference !_scrollbarDragActive " + "so a scrollbar-drag upward scroll inside the window is not swallowed." + ) + + def test_streaming_tick_calls_fix_before_dom_writes(): # The streaming render tick in messages.js must call _fixMobileScrollJank() # before _lastRenderMs=performance.now() so anchor suppression covers every From d10d4f131b7622219eff1fe0c2a9daf2e9b5ce72 Mon Sep 17 00:00:00 2001 From: allenliang2022 Date: Fri, 26 Jun 2026 18:20:58 +0800 Subject: [PATCH 5/6] fix(chat): record keyboard message-pane scroll as intent (#4970 greptile P1) Keyboard scrolling of the message pane (PageUp/PageDown, Arrow keys, Space, Home/End) fires a native scroll event with no wheel/touch/scrollbar/non-message intent. Inside the 1400ms post-render artifact window the suppression branch then returned before movedUp could unpin, so a keyboard scroll-up was swallowed and live-follow snapped the reader back to the bottom. - Add _lastMessageKeyScrollIntentMs + _recentMessageKeyScrollIntent(), stamped by a capture-phase keydown listener on the scroll keys, gated to when the message pane is the scroll target (focused/contains focus/hovered) and not an editable field (composer/input/contenteditable). - Gate the post-render suppression on !_recentMessageKeyScrollIntent() (typeof guard keeps the #4295 node harness inert). - Clear the stamp in both _resetScrollDirectionTracker() and _resetStreamScrollFollow() (same stale-state hygiene as the wheel stamp). Tests: keyboard-scroll-inside-window-still-unpins behavioral regression (harness extended with injected _recentMessageKeyScrollIntent), plus a source lock for the helper/keydown-stamp/suppression-gate/both-resets. test_4856 + test_4295 green (19 passed), node --check clean. --- static/ui.js | 47 ++++++++++++++++- ...est_issue4856_android_scroll_regression.py | 51 ++++++++++++++++++- 2 files changed, 94 insertions(+), 4 deletions(-) diff --git a/static/ui.js b/static/ui.js index 6851d290453..5c4527836c7 100644 --- a/static/ui.js +++ b/static/ui.js @@ -3731,12 +3731,19 @@ let _messageTouchScrollActive=false; let _lastMessageTouchScrollIntentMs=-Infinity; let _deferredOlderMessagesTimer=0; const MESSAGE_TOUCH_SCROLL_SUPPRESS_MS=1200; -// #4970: track recent LOW-DELTA upward message-pane wheel intent separately from +// #4970 review: track recent LOW-DELTA upward message-pane wheel intent separately from // the decisive deltaY<-30 sticky-unpin threshold. A gentle trackpad wheel // (deltaY:-5) is real user intent but never crosses -30, so without this the // post-render artifact suppression would swallow it for the whole window. const MESSAGE_WHEEL_INTENT_SUPPRESS_MS=1200; let _lastMessageWheelIntentMs=-Infinity; +// #4970 review (greptile P1): keyboard scrolling of the message pane (PageUp/Down, +// arrows, Space, Home/End) fires a native `scroll` event with NO wheel/touch/ +// scrollbar/non-message intent. Without recording it, a keyboard scroll-up inside +// the post-render artifact window is swallowed and live-follow snaps the reader +// back to the bottom. Stamp a generic scroll-key intent so the suppression skips it. +const MESSAGE_KEY_SCROLL_INTENT_SUPPRESS_MS=1200; +let _lastMessageKeyScrollIntentMs=-Infinity; let _newMessageCueVisible=false; let _lastMessageRenderAt=-Infinity; function _recentMessageRenderArtifactWindow(ms){ @@ -3757,6 +3764,12 @@ function _recentMessageTouchScrollIntent(){ function _recentMessageWheelIntent(){ return performance.now()-_lastMessageWheelIntentMs{ if(document.visibilityState==='hidden') _scrollbarDragActive=false; },{passive:true}); + // #4970 review (greptile P1): record keyboard-driven message-pane scrolling as + // user intent. PageUp/PageDown, Arrow keys, Space/Shift+Space, Home/End scroll + // the pane and fire a native scroll event with no wheel/touch intent — without + // this stamp a keyboard scroll-up inside the post-render artifact window is + // swallowed and live-follow snaps the reader back to the bottom. Only count it + // when the scroll container (or a descendant) is the active/scrolling target, + // not when typing in the composer. + const _MESSAGE_SCROLL_KEYS=new Set([ + 'PageUp','PageDown','ArrowUp','ArrowDown','Home','End','Spacebar',' ', + ]); + document.addEventListener('keydown',(e)=>{ + if(!e||!_MESSAGE_SCROLL_KEYS.has(e.key)) return; + const a=document.activeElement; + // Ignore keys aimed at editable fields (composer, inputs, contenteditable). + if(a&&(a.tagName==='INPUT'||a.tagName==='TEXTAREA'||a.isContentEditable)) return; + // Count only when the message pane itself is the scroll target: it is focused, + // contains the focus, or the pointer is over it (keyboard scroll w/o focus). + if(a===el||el.contains(a)||el.matches(':hover')){ + _lastMessageKeyScrollIntentMs=performance.now(); + } + },{capture:true,passive:true}); let _scrollRaf=0; el.addEventListener('scroll',()=>{ _scheduleMessageVirtualizedRender(); @@ -4026,16 +4064,21 @@ if(typeof window!=='undefined'){ // manual scrollbar-drag upward scroll inside the window is real intent. // typeof guard keeps the #4295 node harness (no _scrollbarDragActive // injected) inert via short-circuit. + // #4970 review (greptile P1): likewise skip suppression when the reader + // recently scrolled the pane with the keyboard — a keyboard scroll-up is + // real intent that produces a native scroll event with no wheel/touch. if(movedUp && typeof _recentMessageRenderArtifactWindow==='function' && typeof _recentMessageTouchScrollIntent==='function' && typeof _recentNonMessageScrollIntent==='function' && typeof _recentMessageWheelIntent==='function' + && typeof _recentMessageKeyScrollIntent==='function' && (typeof _scrollbarDragActive==='undefined' || !_scrollbarDragActive) && _recentMessageRenderArtifactWindow(1400) && !_recentMessageTouchScrollIntent() && !_recentNonMessageScrollIntent() - && !_recentMessageWheelIntent()){ + && !_recentMessageWheelIntent() + && !_recentMessageKeyScrollIntent()){ _lastScrollTop=top; return; } diff --git a/tests/test_issue4856_android_scroll_regression.py b/tests/test_issue4856_android_scroll_regression.py index 90365d2fa25..e92757c9f73 100644 --- a/tests/test_issue4856_android_scroll_regression.py +++ b/tests/test_issue4856_android_scroll_regression.py @@ -160,7 +160,7 @@ def _scroll_listener_raf_body() -> str: def _run_listener_with_wheel_intent( - samples, *, render_artifact, wheel_intent, scrollbar_drag=False + samples, *, render_artifact, wheel_intent, scrollbar_drag=False, key_scroll=False ): """Run the extracted scroll-listener body in node with controllable stubs. @@ -174,6 +174,7 @@ def _run_listener_with_wheel_intent( "renderArtifact": bool(render_artifact), "wheelIntent": bool(wheel_intent), "scrollbarDrag": bool(scrollbar_drag), + "keyScroll": bool(key_scroll), } script = ( "const payload = " + json.dumps(payload) + ";\n" @@ -199,6 +200,7 @@ def _run_listener_with_wheel_intent( '_recentNonMessageScrollIntent', '_recentMessageWheelIntent', '_scrollbarDragActive', + '_recentMessageKeyScrollIntent', // The extracted listener body uses bare `return;` in the suppression branch. // Wrap it in an inner arrow IIFE so that early return exits the IIFE (not the // outer Function), then read the mutated locals afterward. Without this the @@ -227,6 +229,7 @@ def _run_listener_with_wheel_intent( const noTouch = () => false; const noNonMessage = () => false; const wheelIntent = () => payload.wheelIntent; +const keyScroll = () => payload.keyScroll; for (const sample of payload.samples) { state = step( @@ -249,7 +252,8 @@ def _run_listener_with_wheel_intent( noTouch, noNonMessage, wheelIntent, - payload.scrollbarDrag + payload.scrollbarDrag, + keyScroll ); } @@ -324,6 +328,22 @@ def test_scrollbar_drag_inside_window_still_unpins(self): ) assert state["_scrollPinned"] is False + def test_keyboard_scroll_inside_window_still_unpins(self): + # #4970 review (greptile P1): a keyboard scroll-up (PageUp/Arrow/etc.) + # inside the post-render window is real intent and must NOT be swallowed, + # even with no wheel/touch/scrollbar intent recorded. + state = _run_listener_with_wheel_intent( + self._SAMPLES, + render_artifact=True, + wheel_intent=False, + key_scroll=True, + ) + assert state["_messageUserUnpinned"] is True, ( + "A keyboard scroll-up inside the artifact window must unpin; the " + "suppression must not swallow a recent keyboard scroll intent." + ) + assert state["_scrollPinned"] is False + def test_low_delta_wheel_intent_is_tracked_separately(): # The intent recorder must stamp _lastMessageWheelIntentMs for ANY upward @@ -394,6 +414,33 @@ def test_suppression_gates_on_scrollbar_drag(): ) +def test_keyboard_scroll_intent_tracked_and_gated(): + # #4970 review (greptile P1): keyboard message-pane scrolling must be recorded + # as user intent and excluded from the post-render suppression branch. + assert "let _lastMessageKeyScrollIntentMs=-Infinity" in UI_JS + assert "function _recentMessageKeyScrollIntent" in UI_JS + # A keydown listener must stamp the intent for the pane scroll keys. + assert "_lastMessageKeyScrollIntentMs=performance.now()" in UI_JS, ( + "a keydown handler must stamp _lastMessageKeyScrollIntentMs when the " + "reader uses the keyboard to scroll the message pane." + ) + assert "'PageUp'" in UI_JS and "'PageDown'" in UI_JS + # The suppression branch must consult it. + listener_idx = UI_JS.find("el.addEventListener('scroll'") + listener = UI_JS[listener_idx: listener_idx + 4000] + assert "!_recentMessageKeyScrollIntent()" in listener, ( + "#4970 review: the suppression branch must reference " + "!_recentMessageKeyScrollIntent() so a keyboard scroll-up unpins." + ) + # Both resets must clear the keyboard stamp (stale-state hygiene). + assert "_lastMessageKeyScrollIntentMs=-Infinity" in _extract_fn_body( + "_resetScrollDirectionTracker" + ) + assert "_lastMessageKeyScrollIntentMs=-Infinity" in _extract_fn_body( + "_resetStreamScrollFollow" + ) + + def test_streaming_tick_calls_fix_before_dom_writes(): # The streaming render tick in messages.js must call _fixMobileScrollJank() # before _lastRenderMs=performance.now() so anchor suppression covers every From e84284fd11d1abe3fbec189a3ec737c8d061cced Mon Sep 17 00:00:00 2001 From: allenliang2022 Date: Fri, 26 Jun 2026 21:03:21 +0800 Subject: [PATCH 6/6] fix(chat): do not treat Space on transcript controls as scroll intent (#4970 review) Maintainer/Codex found one narrow edge in the keyboard intent stamp: because the listener runs capture-phase and accepts any focused descendant of #messages, Space/Spacebar on an in-transcript control (tool-card toggles, copy buttons, role buttons, links/tabs) stamped _lastMessageKeyScrollIntentMs before the control handler could preventDefault/stopPropagation. That made a button activation look like a scroll intent and could mask a legitimate post-render artifact. Fix by excluding Space/Spacebar when the event target or active element is an interactive transcript control: button, a[href], select, summary, role=button, role=tab, role=menuitem, or contenteditable. Keep PageUp/PageDown/arrows/Home/End stamping unchanged, and keep the existing INPUT/TEXTAREA/contenteditable composer exclusion. Add a behavioral node-harness test: Space on a focused transcript button leaves the key-scroll stamp at -Infinity (serialized null), while PageUp on the pane still stamps 1234. test_4856 + test_4295 green (20 passed), node --check clean. --- static/ui.js | 13 ++++- ...est_issue4856_android_scroll_regression.py | 56 +++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/static/ui.js b/static/ui.js index 5c4527836c7..19b55ab61fe 100644 --- a/static/ui.js +++ b/static/ui.js @@ -4014,15 +4014,26 @@ if(typeof window!=='undefined'){ // this stamp a keyboard scroll-up inside the post-render artifact window is // swallowed and live-follow snaps the reader back to the bottom. Only count it // when the scroll container (or a descendant) is the active/scrolling target, - // not when typing in the composer. + // not when typing in the composer or activating an in-transcript control. const _MESSAGE_SCROLL_KEYS=new Set([ 'PageUp','PageDown','ArrowUp','ArrowDown','Home','End','Spacebar',' ', ]); + const _isMessageInteractiveKeyTarget=(node)=>{ + if(!node||!el.contains(node)) return false; + if(node.tagName==='INPUT'||node.tagName==='TEXTAREA'||node.isContentEditable) return true; + return !!(node.closest&&node.closest('button,a[href],select,summary,[role="button"],[role="tab"],[role="menuitem"],[contenteditable="true"]')); + }; document.addEventListener('keydown',(e)=>{ if(!e||!_MESSAGE_SCROLL_KEYS.has(e.key)) return; const a=document.activeElement; + const t=e.target; // Ignore keys aimed at editable fields (composer, inputs, contenteditable). if(a&&(a.tagName==='INPUT'||a.tagName==='TEXTAREA'||a.isContentEditable)) return; + // Space/Spacebar activates focused transcript controls (buttons, role=button, + // links, tabs) rather than scrolling. The listener is capture-phase, so target + // handlers have not yet preventDefault()/stopPropagation()'d; inspect the + // active/target control path directly. + if((e.key===' '||e.key==='Spacebar')&&(_isMessageInteractiveKeyTarget(t)||_isMessageInteractiveKeyTarget(a))) return; // Count only when the message pane itself is the scroll target: it is focused, // contains the focus, or the pointer is over it (keyboard scroll w/o focus). if(a===el||el.contains(a)||el.matches(':hover')){ diff --git a/tests/test_issue4856_android_scroll_regression.py b/tests/test_issue4856_android_scroll_regression.py index e92757c9f73..e66dbe7c0af 100644 --- a/tests/test_issue4856_android_scroll_regression.py +++ b/tests/test_issue4856_android_scroll_regression.py @@ -439,6 +439,62 @@ def test_keyboard_scroll_intent_tracked_and_gated(): assert "_lastMessageKeyScrollIntentMs=-Infinity" in _extract_fn_body( "_resetStreamScrollFollow" ) + assert "_isMessageInteractiveKeyTarget" in UI_JS + assert "button,a[href],select,summary" in UI_JS + + +@pytest.mark.skipif(NODE is None, reason="node not on PATH") +def test_space_on_transcript_button_does_not_stamp_key_scroll_intent(): + # Maintainer MUST-FIX: Space on a focused transcript control activates the + # control; it is NOT a scroll. Because the handler is capture-phase, it must + # inspect the target/active element directly rather than rely on defaultPrevented. + start = UI_JS.index("const _MESSAGE_SCROLL_KEYS=new Set") + end = UI_JS.index(" let _scrollRaf=0;", start) + region = UI_JS[start:end] + script = ( + "const region = " + json.dumps(region) + ";\n" + + r""" +let _lastMessageKeyScrollIntentMs = -Infinity; +const performance = { now: () => 1234 }; +const el = { + contains(node){ return !!(node && node.inMessages); }, + matches(sel){ return sel === ':hover'; }, +}; +const document = { + activeElement: null, + _handler: null, + addEventListener(type, fn){ if(type === 'keydown') this._handler = fn; }, +}; +function makeNode({tag='DIV', inMessages=true, interactive=false, editable=false}={}){ + return { + tagName: tag, + inMessages, + isContentEditable: editable, + closest(sel){ return interactive ? this : null; }, + }; +} +// Run via a closure so the stamped variable lives with the extracted handler. +const env = Function('el','document','performance', `let _lastMessageKeyScrollIntentMs=-Infinity; ${region}\nreturn {handler:document._handler, get:()=>_lastMessageKeyScrollIntentMs, setActive:(n)=>{document.activeElement=n;}};`)(el, document, performance); +const button = makeNode({tag:'BUTTON', interactive:true}); +env.setActive(button); +env.handler({key:' ', target:button}); +const afterSpace = env.get(); +const pane = makeNode({tag:'DIV', interactive:false}); +env.setActive(pane); +env.handler({key:'PageUp', target:pane}); +const afterPageUp = env.get(); +console.log(JSON.stringify({afterSpace, afterPageUp})); +""" + ) + result = subprocess.run( + [NODE, "-e", script], check=True, capture_output=True, text=True, timeout=30 + ) + state = json.loads(result.stdout.strip()) + assert state["afterSpace"] is None, ( + "JSON serializes -Infinity as null; Space on a focused transcript button " + "must leave the stamp at -Infinity/null." + ) + assert state["afterPageUp"] == 1234 def test_streaming_tick_calls_fix_before_dom_writes():