Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

Chat: the transcript follows the answer only while the reader has not left; a wheel notch, finger or key moving up lets go at once, in the app chat and the served web page (#4014)

Niko122189a68d8829b9
diff --git a/apps/host/src/lib/follow-scroll.ts b/apps/host/src/lib/follow-scroll.ts
new file mode 100644
index 000000000..25da25193
--- /dev/null
+++ b/apps/host/src/lib/follow-scroll.ts
@@ -0,0 +1,38 @@
+/**
+ * When a chat follows the newest token, and when the reader has let go (#4014).
+ *
+ * The old rule asked "is the reader within 120 px of the bottom?" on every streamed token and pulled the view
+ * back if so. One wheel notch is about 100 px, so it always landed inside that band and was undone by the next
+ * token; only a scrollbar drag, which jumps further, got away. The rule now follows what the reader did:
+ * a wheel, finger or key moving up lets go at once, and the chat follows again when the reader is back at
+ * the bottom.
+ */
+export interface Scroller { scrollHeight: number; scrollTop: number; clientHeight: number }
+
+/** Pixels of slack that still count as "at the bottom" (the same as `atBottom` in reasoning.ts). */
+export const FOLLOW_SLACK = 24;
+/** Past this far from the bottom the "jump to latest" button is offered. */
+export const PILL_DISTANCE = 400;
+/** A scroll this soon after the reader's own input was the reader's. */
+export const INPUT_WINDOW_MS = 400;
+
+export const distanceFromBottom = (el: Scroller): number => el.scrollHeight - el.scrollTop - el.clientHeight;
+
+/**
+ * Whether the chat should keep following after a scroll event.
+ * - back at the bottom: follow again;
+ * - the reader moved it (a wheel, finger, key or the scrollbar a moment ago) and it is not at the bottom: let go;
+ * - far away whatever moved it (a jump): let go;
+ * - otherwise (the page grew under a following reader and no input came): keep the state it had.
+ */
+export function followAfterScroll(distance: number, wasFollowing: boolean, msSinceInput: number): boolean {
+ if (distance <= FOLLOW_SLACK) return true;
+ if (msSinceInput <= INPUT_WINDOW_MS || distance > PILL_DISTANCE) return false;
+ return wasFollowing;
+}
+
+/** A wheel turned up (negative delta) or a finger dragging the content down: the reader wants to go back. */
+export const wheelLeavesBottom = (deltaY: number): boolean => deltaY < 0;
+
+/** Keys that move a scroller up. */
+export const KEYS_UP = new Set(['PageUp', 'ArrowUp', 'Home']);
diff --git a/apps/host/src/screens/Chat.tsx b/apps/host/src/screens/Chat.tsx
index 97dc34f2c..385c3acc7 100644
--- a/apps/host/src/screens/Chat.tsx
+++ b/apps/host/src/screens/Chat.tsx
@@ -40,6 +40,7 @@ import { composerCap, scrollBehavior } from '../lib/responsive';
import { relTime, cx, duration, tokens, tps } from '../lib/format';
import { createSubagentExample, pushToast, setPreviewTabClosed, branchFrom, continueLast, markRead, resolveTool, retryLast, selectSession, rewindTo, sendMessage, stopStreaming, useStore, } from '../lib/store';
import { copyText } from '../lib/clipboard';
+import { KEYS_UP, PILL_DISTANCE, distanceFromBottom, followAfterScroll, wheelLeavesBottom } from '../lib/follow-scroll';
import { getSlashCommands } from '../lib/commands';
import { useLocation } from '../lib/router';
import { composerSends } from '../lib/shortcut-bindings';
@@ -212,6 +213,8 @@ export function ChatScreen() {
}, [streaming]);
/** Whether the reader is following the newest message rather than reading back. */
const pinned = useRef(true);
+ /** When the reader last used the wheel, a finger, a key or the scrollbar on the transcript. */
+ const readerInput = useRef(0);
/**
* Scrolls to the newest message and stays there.
*
@@ -266,8 +269,9 @@ export function ChatScreen() {
const el = scroller.current;
if (!el || (session?.showcase && !streaming))
return;
- const nearBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 120;
- if (nearBottom)
+ // The reader's own scrolling decides (#4014): a wheel notch is about 100 px and used to land inside a 120 px band that pulled
+ // the view back on every token. `pinned` is set by the scroller's wheel, touch, key and scroll handlers below.
+ if (pinned.current)
scrollToLatest();
}, [session?.messages.length, session?.messages.at(-1)?.content, scrollToLatest]);
// Scroll position is remembered per conversation, so returning to one puts you
@@ -421,9 +425,17 @@ export function ChatScreen() {
// the way back is worth offering.
// The threshold has to tolerate the height estimate moving under
// us, or the pill flickers as turns render during a scroll.
- const away = el.scrollHeight - el.scrollTop - el.clientHeight > 400;
- pinned.current = !away;
- setAwayFromBottom(away);
+ const distance = distanceFromBottom(el);
+ pinned.current = followAfterScroll(distance, pinned.current, Date.now() - readerInput.current);
+ setAwayFromBottom(distance > PILL_DISTANCE);
+ }} onWheel={(e) => {
+ readerInput.current = Date.now();
+ if (wheelLeavesBottom(e.deltaY) && e.currentTarget.scrollTop > 0)
+ pinned.current = false;
+ }} onTouchMove={() => { readerInput.current = Date.now(); }} onPointerDown={() => { readerInput.current = Date.now(); }} onKeyDown={(e) => {
+ readerInput.current = Date.now();
+ if (KEYS_UP.has(e.key) && e.target === e.currentTarget && e.currentTarget.scrollTop > 0)
+ pinned.current = false;
}}>
<div className="chat__inner">
diff --git a/apps/host/tests/follow-scroll.test.mjs b/apps/host/tests/follow-scroll.test.mjs
new file mode 100644
index 000000000..e724696a7
--- /dev/null
+++ b/apps/host/tests/follow-scroll.test.mjs
@@ -0,0 +1,39 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import { transform } from 'esbuild';
+
+const { code } = await transform(await readFile(new URL('../src/lib/follow-scroll.ts', import.meta.url), 'utf8'), { loader: 'ts', format: 'esm' });
+const f = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
+
+test('a wheel notch up while an answer streams lets go at once (#4014)', () => {
+ assert.equal(f.wheelLeavesBottom(-100), true);
+ assert.equal(f.wheelLeavesBottom(100), false);
+ // the notch lands about 100 px from the bottom, inside the old 120 px band: it must not be pulled back
+ assert.equal(f.followAfterScroll(100, true, 20), false);
+ assert.equal(f.followAfterScroll(40, true, 20), false);
+});
+
+test('back at the bottom the chat follows again, by wheel, key, drag or the jump button', () => {
+ assert.equal(f.followAfterScroll(0, false, 10_000), true);
+ assert.equal(f.followAfterScroll(f.FOLLOW_SLACK, false, 10_000), true);
+ assert.equal(f.followAfterScroll(f.FOLLOW_SLACK + 1, false, 10_000), false);
+});
+
+test('the page growing under a following reader does not make the chat let go', () => {
+ // no input from the reader for a while, a few lines of the answer arrived: keep following
+ assert.equal(f.followAfterScroll(80, true, 5_000), true);
+ // a reader who had let go stays away while the answer grows
+ assert.equal(f.followAfterScroll(80, false, 5_000), false);
+ // far away whatever moved it (a scrollbar drag or a jump)
+ assert.equal(f.followAfterScroll(f.PILL_DISTANCE + 1, true, 5_000), false);
+});
+
+test('the chat screen uses the reader-driven rule, not the 120 px band', async () => {
+ const chat = await readFile(new URL('../src/screens/Chat.tsx', import.meta.url), 'utf8');
+ assert.doesNotMatch(chat, /clientHeight < 120/);
+ assert.match(chat, /followAfterScroll\(/);
+ assert.match(chat, /onWheel=/);
+ // an upward wheel on a transcript that cannot scroll must not switch following off
+ assert.match(chat, /wheelLeavesBottom\(e\.deltaY\) && e\.currentTarget\.scrollTop > 0/);
+});
diff --git a/serve/test_web_follow.py b/serve/test_web_follow.py
new file mode 100644
index 000000000..5157ef988
--- /dev/null
+++ b/serve/test_web_follow.py
@@ -0,0 +1,62 @@
+"""serve/test_web_follow.py - the web chat follows the answer only while the reader has not left (#4014).
+
+The page used to pull the view back to the bottom on every frame when it was within 120 px of it, so one wheel notch
+(about 100 px) could not scroll up while an answer streamed. Pins, with node, the page's own rule and that the wheel,
+touch and keyboard listeners are wired. Skipped without node.
+
+ python -m unittest serve.test_web_follow -v
+"""
+from __future__ import annotations
+
+import json
+import shutil
+import subprocess
+import unittest
+from pathlib import Path
+
+APP = Path(__file__).resolve().parent / "web" / "app.js"
+
+
+def between(src: str, start: str, end: str) -> str:
+ a = src.index(start)
+ return src[a:src.index(end, a)]
+
+
[email protected](shutil.which("node"), "node is not installed")
+class WebFollow(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.src = APP.read_text(encoding="utf-8")
+ cls.rule = between(cls.src, "const FOLLOW_SLACK", "function scrollDown")
+
+ def follow(self, distance, was, ms):
+ js = self.rule + f"\nconsole.log(JSON.stringify(followAfterScroll({distance}, {json.dumps(was)}, {ms})));"
+ out = subprocess.run(["node", "-e", js], capture_output=True, text=True, timeout=30)
+ self.assertEqual(out.returncode, 0, out.stderr)
+ return json.loads(out.stdout)
+
+ def test_a_wheel_notch_inside_the_old_band_is_not_pulled_back(self):
+ self.assertFalse(self.follow(100, True, 20))
+ self.assertFalse(self.follow(40, True, 20))
+
+ def test_back_at_the_bottom_it_follows_again(self):
+ self.assertTrue(self.follow(0, False, 10_000))
+ self.assertTrue(self.follow(24, False, 10_000))
+ self.assertFalse(self.follow(25, False, 10_000))
+
+ def test_the_page_growing_under_a_following_reader_keeps_following(self):
+ self.assertTrue(self.follow(80, True, 5_000))
+ self.assertFalse(self.follow(80, False, 5_000))
+ self.assertFalse(self.follow(401, True, 5_000))
+
+ def test_the_old_120_px_rule_is_gone_and_the_reader_input_is_wired(self):
+ self.assertNotIn("< 120", between(self.src, "function renderChat", "$(\"chat\").addEventListener(\"click\""))
+ watch = between(self.src, "(function watchReader()", "})();")
+ for event in ("wheel", "touchmove", "pointerdown", "keydown", "scroll"):
+ self.assertIn(f'"{event}"', watch)
+ # a wheel up on a chat that cannot scroll must not switch following off
+ self.assertIn("e.deltaY < 0 && s.scrollTop > 0", watch)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/serve/web/app.js b/serve/web/app.js
index ac84f85dc..5dedc3531 100644
--- a/serve/web/app.js
+++ b/serve/web/app.js
@@ -716,8 +716,36 @@ function renderChat() {
messages.forEach((m, i) => chat.appendChild(msgEl(m, i)));
scrollDown(true);
}
-function nearBottom() { const s = $("chat-scroll"); return s.scrollHeight - s.scrollTop - s.clientHeight < 120; }
-function scrollDown(force) { const s = $("chat-scroll"); if (force || nearBottom()) s.scrollTop = s.scrollHeight; }
+// Follow the answer while the reader has not left (#4014). Asking "am I within 120 px of the bottom?" on every frame pulled
+// the view back after every wheel notch (a notch is about 100 px), so scrolling up during a long answer only worked by
+// dragging the scrollbar. Now the reader's own input lets go (wheel up, a finger or a key moving up, the scrollbar), and a
+// scroll back to the bottom follows again.
+let stickToBottom = true, lastReaderInput = 0;
+const FOLLOW_SLACK = 24, FAR_AWAY = 400, INPUT_WINDOW_MS = 400;
+function followAfterScroll(distance, wasFollowing, msSinceInput) {
+ if (distance <= FOLLOW_SLACK) return true;
+ if (msSinceInput <= INPUT_WINDOW_MS || distance > FAR_AWAY) return false;
+ return wasFollowing;
+}
+function scrollDown(force) {
+ const s = $("chat-scroll");
+ if (force) stickToBottom = true;
+ if (stickToBottom) s.scrollTop = s.scrollHeight;
+}
+(function watchReader() {
+ const s = $("chat-scroll");
+ const touch = () => { lastReaderInput = Date.now(); };
+ s.addEventListener("wheel", (e) => { touch(); if (e.deltaY < 0 && s.scrollTop > 0) stickToBottom = false; }, {passive: true});
+ s.addEventListener("touchmove", touch, {passive: true});
+ s.addEventListener("pointerdown", touch, {passive: true});
+ s.addEventListener("keydown", (e) => {
+ touch();
+ if (["PageUp", "ArrowUp", "Home"].includes(e.key) && e.target === s && s.scrollTop > 0) stickToBottom = false;
+ });
+ s.addEventListener("scroll", () => {
+ stickToBottom = followAfterScroll(s.scrollHeight - s.scrollTop - s.clientHeight, stickToBottom, Date.now() - lastReaderInput);
+ }, {passive: true});
+})();
$("chat").addEventListener("click", (e) => {
const cc = e.target.closest("[data-code-copy]");