World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
Keep a streaming answer from pulling a reader who scrolled up back to the bottom (#930)
Maya Kidda23a65dff51
diff --git a/web/src/chatScroll.test.ts b/web/src/chatScroll.test.tsnew file mode 100644index 00000000..7a523d7e--- /dev/null+++ b/web/src/chatScroll.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from "vitest";+import { FOLLOW_SLACK_PX, followsBottom } from "./chatScroll";++/** 视口 600、内容 2000:滚到 1400 就是底 */+const view = (scrollTop: number, clientHeight = 600, scrollHeight = 2000) => ({+ scrollTop,+ clientHeight,+ scrollHeight,+});++describe("following a streaming answer", () => {+ it("a reader at the bottom follows the answer", () => {+ expect(followsBottom(view(1400))).toBe(true);+ });++ it("a reader within the slack still counts as at the bottom", () => {+ expect(followsBottom(view(1400 - FOLLOW_SLACK_PX))).toBe(true);+ });++ it("a reader who scrolled up stays where they are", () => {+ expect(followsBottom(view(1400 - FOLLOW_SLACK_PX - 1))).toBe(false);+ expect(followsBottom(view(1200))).toBe(false);+ expect(followsBottom(view(0))).toBe(false);+ });++ it("a conversation shorter than the view has nowhere to scroll away to", () => {+ expect(followsBottom(view(0, 600, 400))).toBe(true);+ });+});diff --git a/web/src/chatScroll.ts b/web/src/chatScroll.tsnew file mode 100644index 00000000..1f571e85--- /dev/null+++ b/web/src/chatScroll.ts@@ -0,0 +1,21 @@+// 回答在往外写的时候,画面跟不跟着往下走。+//+// 从前 `shown` 每变一次就把底部的哨兵滚进视野,而生成期间 liveAnswer 每 33ms 通知一次:+// 往上翻着读前文(轨迹、上一轮回答、引用)的人,每 33ms 被拽回底部一次。一个正在写的+// 回答让屏幕上别的东西都读不成。+//+// 判据改成**人此刻停在哪**:停在底部就跟着新写出的字走;翻上去了就留在原地,自己滚回+// 底部再接着跟。「底部」留一点余量——列表底下有 pb-12 的留白,换行与缩放也会让最后+// 几像素对不齐。要求分毫不差的话,一个一直停在底部的人会被当成「翻上去了」而跟丢。++/** 离底部多近算「在跟着读」,CSS 像素 */+export const FOLLOW_SLACK_PX = 48;++/** 这个滚动容器此刻是不是停在底部。内容比视口短时恒为真:没有地方可以翻走 */+export function followsBottom(el: {+ scrollTop: number;+ clientHeight: number;+ scrollHeight: number;+}): boolean {+ return el.scrollHeight - el.scrollTop - el.clientHeight <= FOLLOW_SLACK_PX;+}diff --git a/web/src/pages/Chat.tsx b/web/src/pages/Chat.tsxindex 3cedaa19..a05d4bc1 100644--- a/web/src/pages/Chat.tsx+++ b/web/src/pages/Chat.tsx@@ -39,6 +39,7 @@ import {} from "../api";import { S } from "../i18n";import { rehypeCitations } from "../citations";+import { followsBottom } from "../chatScroll";import { chatMarkdown, SourceList, SourcesProvider } from "./chatCitations";import { toast } from "../toast";import {@@ -116,6 +117,9 @@ export function Chat() {// 路由同步 effect 的判据:state 的提交时序晚于 navigate 触发的重渲染,// 用 ref 同步写入才能让"流式新建后仅换 URL"的守卫可靠命中const activeIdRef = useRef<string | null>(null);+ // 读者是不是停在对话底部(见 chatScroll.ts)。换会话、发新消息都回到「跟着」:+ // 那一刻人要看的就是底部+ const following = useRef(true);// 已经结束的那些轮次,从库里读来。**进行中的那一次不在这里**——见下const [turns, setTurns] = useState<Turn[]>([]);const [loadedKey, setLoadedKey] = useState<string | null>(null);@@ -141,6 +145,7 @@ export function Chat() {// loadConversation 必须先检查 liveAnswer.entry,直接认领,避免流中途读库覆盖。claimView(routeConvId ?? null);activeIdRef.current = null;+ following.current = true;setActiveId(routeConvId ?? null);setTurns([]);setLoadedKey(null);@@ -238,9 +243,10 @@ export function Chat() {onError: (e: Error) => toast.error(e.message),});- // 直落底部(instant):平滑滚动在流式追加下会一路慢爬+ // 直落底部(instant):平滑滚动在流式追加下会一路慢爬。**只在人停在底部时落**:+ // 生成期间 `shown` 每 33ms 变一次,翻上去读前文的人不该被每一批新字拽回来useEffect(() => {- bottomRef.current?.scrollIntoView({ behavior: "instant" });+ if (following.current) bottomRef.current?.scrollIntoView({ behavior: "instant" });}, [shown]);// 路由 → 会话装载;裸 /chat 还原本库上次会话(切页回来仍在原对话)@@ -401,6 +407,7 @@ export function Chat() {// 同样不 abort:开一场新的不等于放弃上一场if (kb) sessionStorage.removeItem(lastKey(kb.id));activeIdRef.current = null;+ following.current = true;setActiveId(null);setTurns([]);navigate({ to: "/kb/$kbId/chat", params: { kbId } });@@ -423,6 +430,7 @@ export function Chat() {const q = input.trim();if (!q || streaming || !kb || kb.id !== kbId || loadingHistory || historyError) return;const owner = claimView(activeId);+ following.current = true;setIdleHistoryKey(null);setInput("");sessionStorage.removeItem(DRAFT_KEY);@@ -784,7 +792,12 @@ export function Chat() {</div>) : (<>- <div className="flex-1 overflow-y-auto u-scroll u-chat-fade px-4 pt-6 pb-12">+ <div+ className="flex-1 overflow-y-auto u-scroll u-chat-fade px-4 pt-6 pb-12"+ onScroll={(e) => {+ following.current = followsBottom(e.currentTarget);+ }}+ ><div className="max-w-3xl mx-auto space-y-4">{shown.map((t, i) => (<TurnView key={i} turn={t} live={streaming && i === shown.length - 1} />diff --git a/web/tests/chat-view.test.mjs b/web/tests/chat-view.test.mjsindex bc54b0eb..8b7514a1 100644--- a/web/tests/chat-view.test.mjs+++ b/web/tests/chat-view.test.mjs@@ -646,5 +646,85 @@ test(}},);++ await t.test(+ "a reader who scrolled up stays put while an answer streams",+ async () => {+ const history = Array.from({ length: 40 }, (_, i) =>+ message(`Turn ${i}`, i % 2 ? "assistant" : "user"),+ );+ const f = await open("/kb/one/chat/a", async (route, p) => {+ if (p.endsWith("/conversations/a")) {+ await route.fulfill({ json: { messages: history } });+ return true;+ }+ });+ try {+ await f.page.getByText("Turn 39", { exact: true }).waitFor();+ const view = f.page.locator(".u-chat-fade");+ // This fixture loads no stylesheet, so the transcript is not a scroll box by+ // itself: give it the bounded height and overflow the app's layout gives it.+ await view.evaluate((el) => {+ el.style.height = "400px";+ el.style.overflowY = "auto";+ });+ // The answer grows through the same store a POST writes into.+ await f.page.evaluate(() => {+ const turns = Array.from({ length: 40 }, (_, i) => ({+ role: i % 2 ? "assistant" : "user",+ content: `Turn ${i}`,+ }));+ window.__answer = window.__live.begin(+ "one",+ "a",+ [+ ...turns,+ { role: "user", content: "And then?" },+ { role: "assistant", content: "" },+ ],+ () => {},+ );+ });+ const grow = async () => {+ for (let i = 0; i < 5; i++) {+ await f.page.evaluate(() =>+ window.__answer.patchLast((turn) => ({+ ...turn,+ content: `${turn.content}One more line of the answer.\n\n`,+ })),+ );+ await f.page.waitForTimeout(60);+ }+ };+ assert.ok(+ await view.evaluate((el) => el.scrollHeight > el.clientHeight + 200),+ "the transcript must be taller than the view",+ );+ // Scrolled up to read: the growing answer leaves the reader where they are.+ await view.evaluate((el) => {+ el.scrollTop = 0;+ });+ await f.page.waitForTimeout(60);+ await grow();+ assert.equal(await view.evaluate((el) => el.scrollTop), 0);+ // Back at the bottom: the answer is followed again.+ await view.evaluate((el) => {+ el.scrollTop = el.scrollHeight;+ });+ await f.page.waitForTimeout(60);+ await grow();+ assert.ok(+ await view.evaluate(+ (el) => el.scrollHeight - el.scrollTop - el.clientHeight <= 48,+ ),+ "a reader at the bottom follows the answer",+ );+ await f.page.evaluate(() => window.__answer.finish());+ assert.deepEqual(f.errors, []);+ } finally {+ await f.close();+ }+ },+ );},);