A local-first multi-agent app development platform, built on PenguinHarness
fix(web): loading an earlier page of a conversation leaves the reader where they were (#995)
lmliheng2428ebbd8d52
diff --git a/changelog/unreleased/2026-10-12-history-prepend-anchor.md b/changelog/unreleased/2026-10-12-history-prepend-anchor.mdnew file mode 100644index 00000000..265829b5--- /dev/null+++ b/changelog/unreleased/2026-10-12-history-prepend-anchor.md@@ -0,0 +1,17 @@+# Loading an earlier page of a conversation leaves the reader where they were++- **Date:** 2026-10-12+- **Type:** fix+- **Scope:** `web`++[中文版](2026-10-12-history-prepend-anchor.zh.md)++Ported from upstream PenguinHarness (#995, commit `5b096c2e`).++Scrolling to the top of a conversation fetches the earlier page and places it above what is shown. The reader used to be pushed down by that whole page, or thrown to the end of the conversation; now the message they were reading stays where it was.++- The rendered list and the prepend correction change in the same render: the list's memo is keyed on the prepended content itself, not only on a throttled version number.+- The correction is measured, not assumed: the oldest visible prompt's position is recorded at every scroll and render, and after a prepend the view is moved by however far that prompt actually moved. The browser's own scroll anchoring compensates away from the top and not at offset 0, so a fixed height-delta correction applied twice or not at all.+- The loading row at the top keeps its height whenever history lies above, so its appearing and disappearing no longer shift the transcript.++Paging itself, the server and the stream controller are unchanged.diff --git a/changelog/unreleased/2026-10-12-history-prepend-anchor.zh.md b/changelog/unreleased/2026-10-12-history-prepend-anchor.zh.mdnew file mode 100644index 00000000..5f810c69--- /dev/null+++ b/changelog/unreleased/2026-10-12-history-prepend-anchor.zh.md@@ -0,0 +1,17 @@+# 往上翻页加载更早的对话时,读者停在原来读的那条消息上++- **Date:** 2026-10-12+- **Type:** fix+- **Scope:** `web`++[English](2026-10-12-history-prepend-anchor.md)++移植自上游 PenguinHarness(#995,提交 `5b096c2e`)。++对话页滚到顶部会取回更早的一页,插到已有内容的上方。以前读者会被新插入的一整页推走,或被甩到对话最底部;现在正在读的那条消息留在原处。++- 消息列表与滚动修正在同一次渲染里变化:列表的缓存以已插入的内容本身为键,而不只是一个被节流的版本号。+- 修正量是量出来的,不是假设的:每次滚动和渲染都记下最靠上那条提问在屏幕上的位置,插入之后按它实际被挪动的距离修正。浏览器自己的滚动锚定在非顶端会补偿、在顶端不会,按高度差固定修正要么重复要么缺失。+- 顶部的加载行在上方还有历史时一直保留高度,出现和消失不再挪动对话。++分页本身、服务端和流控制器不变。diff --git a/packages/web/e2e/history-prepend-anchor.spec.mjs b/packages/web/e2e/history-prepend-anchor.spec.mjsnew file mode 100644index 00000000..d3638cc0--- /dev/null+++ b/packages/web/e2e/history-prepend-anchor.spec.mjs@@ -0,0 +1,185 @@+/**+ * Prepend scroll anchoring on main (unit-windowed history: TAIL_UNITS = OLDER_UNITS = 20).+ *+ * One Session is driven to 45 exchanges, so a fresh open loads the newest 20 turns and a+ * scroll to the top prepends the previous 20. For each starting scroll offset the spec+ * records where a visible prompt sits in the viewport before the prepend and after it+ * lands, plus a per-frame trace of that prompt's position in between. It reports numbers+ * (lines prefixed ANCHOR) and asserts the reader stays within 2px.+ *+ * START_TOPS (env, comma separated) overrides the starting offsets; default "0,150,0,150".+ */+import { test, expect } from "@playwright/test";+import { provisionAndLogin } from "./auth.mjs";++const BASE = process.env.BASE_URL;+const MOCK = process.env.MOCK_URL;+const U = "anchoruser";+const P = "password123";+const TURNS = 45;+const STARTS = (process.env.START_TOPS ?? "0,150,0,150").split(",").map(Number);++test.use({ viewport: { width: 1440, height: 860 } });++/** Reply completion marker: every mock turn-2 ends with this exact sentence. */+const REPLY = "Command finished";++async function setup(page) {+ await provisionAndLogin(page.request, U, P);+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();+ const projectId = projects.projects[0].projectId;+ const put = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {+ data: {+ defaultModel: { provider: "custom", modelId: "claude-4-8" },+ models: [+ {+ provider: "custom",+ modelId: "claude-4-8",+ apiKey: "sk-mock",+ baseUrl: MOCK,+ contextWindow: 200000,+ },+ ],+ },+ });+ expect(put.ok(), "put models").toBeTruthy();+ const res = await (+ await page.request.post(`${BASE}/api/projects/${projectId}/agents/default_agent/sessions`, {+ data: { provider: "custom", modelId: "claude-4-8", approvalMode: "allow-all" },+ })+ ).json();+ return res.session.sessionId;+}++const sender = (page, ta) => async (text, replies) => {+ await ta.click();+ await ta.fill(text);+ await page.keyboard.press("Enter");+ await page.waitForFunction(+ ([marker, want]) => document.body.innerText.split(marker).length - 1 >= want,+ [REPLY, replies],+ { timeout: 60000 },+ );+};++const prompts = (page) => page.locator("[data-outline-anchor]");++test("a prepended window leaves the reader where they were (measured)", async ({ page }) => {+ test.setTimeout(600_000);+ const sessionId = await setup(page);+ await page.goto(`${BASE}/chat/${sessionId}`);+ const ta = page.getByPlaceholder(/输入消息/);+ await ta.waitFor();+ const send = sender(page, ta);+ for (let n = 1; n <= TURNS; n += 1) await send(`第 ${n} 问`, n);++ const results = [];+ for (const startTop of STARTS) {+ const requests = [];+ const onReq = (r) => {+ if (r.url().includes("/messages")) requests.push(r.url().replace(BASE, ""));+ };+ page.on("request", onReq);+ await page.reload();+ await expect(prompts(page).first()).toBeVisible();+ await expect(page.getByText(`第 ${TURNS} 问`, { exact: true }).first()).toBeVisible();+ await page.waitForTimeout(1500);+ const opened = await prompts(page).count();+ expect(opened, "opens on a window, not the whole transcript").toBeLessThan(TURNS);++ // Scroll, pick the first prompt inside the viewport, measure it and start a per-frame+ // trace in ONE synchronous evaluation: the fetch the scroll triggers is asynchronous,+ // so nothing can land between the scroll and the first measurement.+ const before = await page.evaluate((top) => {+ const first = document.querySelector("[data-outline-anchor]");+ const c = first.closest(".overflow-y-auto");+ c.scrollTop = top;+ const ct = c.getBoundingClientRect().top;+ const node = [...document.querySelectorAll("[data-outline-anchor]")].find(+ (n) => n.getBoundingClientRect().top >= ct,+ );+ const key = node.getAttribute("data-outline-anchor");+ const trace = [];+ window.__anchorTrace = trace;+ window.__anchorStop = false;+ const t0 = performance.now();+ const tick = () => {+ const n = document.querySelector(`[data-outline-anchor="${key}"]`);+ trace.push({+ t: Math.round(performance.now() - t0),+ top: n ? Math.round(n.getBoundingClientRect().top * 10) / 10 : null,+ scrollTop: Math.round(c.scrollTop * 10) / 10,+ scrollHeight: c.scrollHeight,+ count: document.querySelectorAll("[data-outline-anchor]").length,+ });+ if (!window.__anchorStop) requestAnimationFrame(tick);+ };+ requestAnimationFrame(tick);+ return {+ key,+ top: node.getBoundingClientRect().top,+ scrollTop: c.scrollTop,+ scrollHeight: c.scrollHeight,+ clientHeight: c.clientHeight,+ text: node.textContent.slice(0, 20),+ };+ }, startTop);++ await expect.poll(() => prompts(page).count(), { timeout: 20000 }).toBeGreaterThan(opened);+ const measure = () =>+ page.evaluate((key) => {+ const n = document.querySelector(`[data-outline-anchor="${key}"]`);+ const c = n.closest(".overflow-y-auto");+ return {+ top: n.getBoundingClientRect().top,+ scrollTop: c.scrollTop,+ scrollHeight: c.scrollHeight,+ count: document.querySelectorAll("[data-outline-anchor]").length,+ };+ }, before.key);+ const landed = await measure();+ await page.waitForTimeout(1000);+ const settled = await measure();+ const trace = await page.evaluate(() => {+ window.__anchorStop = true;+ return window.__anchorTrace;+ });+ page.off("request", onReq);+ // Compress the trace to the frames where anything changed.+ const changes = trace.filter(+ (f, i) =>+ i === 0 ||+ f.top !== trace[i - 1].top ||+ f.scrollTop !== trace[i - 1].scrollTop ||+ f.scrollHeight !== trace[i - 1].scrollHeight ||+ f.count !== trace[i - 1].count,+ );+ const r = {+ startTop,+ opened,+ prompt: before.text,+ before,+ landed,+ settled,+ displacementLanded: Math.round((landed.top - before.top) * 10) / 10,+ displacementSettled: Math.round((settled.top - before.top) * 10) / 10,+ grew: settled.scrollHeight - before.scrollHeight,+ requests,+ changes,+ };+ results.push(r);+ console.log(`ANCHOR ${JSON.stringify(r)}`);+ }+ for (const r of results) {+ console.log(+ `ANCHOR-SUMMARY start=${r.startTop} opened=${r.opened} loaded=${r.settled.count} ` ++ `grew=${r.grew}px displacement(landed)=${r.displacementLanded}px ` ++ `displacement(settled)=${r.displacementSettled}px scrollTop ${r.before.scrollTop} -> ${r.settled.scrollTop}`,+ );+ }+ for (const r of results) {+ expect+ .soft(Math.abs(r.displacementSettled), `start ${r.startTop}: reader displaced`)+ .toBeLessThanOrEqual(2);+ }+});diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex 1a3519ae..d0badee0 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -554,14 +554,18 @@ export function ChatPage() {} = useSessionDraft(selected?.sessionId ?? null);// The rendered transcript: backfilled older windows (frozen items, negative ids) ahead- // of the live tail model's items. Version keys the memo — a prepend bumps it.+ // of the live tail model's items. Keyed on the prefix's identity as well as the stream+ // version: the controller prepends synchronously and its repaint signal is throttled, so+ // a render forced by anything else in between must not pair the NEW prepend count (read+ // live below) with the OLD item list — the stream would anchor against a layout that has+ // not changed yet and leave the commit that does change it unanchored.const allItems = useMemo(() =>stream.prefixItems.length > 0? [...stream.prefixItems, ...stream.model.items]: stream.model.items,// eslint-disable-next-line react-hooks/exhaustive-deps- [stream.version, routeSessionId],+ [stream.version, stream.prefixItems, routeSessionId],);// Derivations over the stream items (the model mutates in place, so `version` — its own// repaint signal — keys the memos; the session id covers a switch racing a same-valueddiff --git a/packages/web/src/features/chat/message-stream.tsx b/packages/web/src/features/chat/message-stream.tsxindex 3482f216..5776cf86 100644--- a/packages/web/src/features/chat/message-stream.tsx+++ b/packages/web/src/features/chat/message-stream.tsx@@ -279,6 +279,21 @@ export function MessageStream({olderRef.current = older;const lastPrependedRef = useRef(older?.prependedCount ?? 0);const lastHeightRef = useRef(0);+ /**+ * Where the oldest loaded prompt sat in the viewport at the last scroll or commit: what+ * a prepend restores. A window landing above pushes it down by the window's height, and+ * the browser's own scroll anchoring may or may not have compensated already (it does+ * away from the top, never at scroll offset 0), so the correction is measured on the+ * node itself rather than assumed from the height delta — which would apply it twice.+ */+ const anchorRef = useRef<{ id: string; top: number } | null>(null);+ const recordAnchor = (el: HTMLDivElement) => {+ const node = el.querySelector<HTMLElement>("[data-outline-anchor]");+ anchorRef.current =+ node === null+ ? null+ : { id: node.dataset.outlineAnchor ?? "", top: node.getBoundingClientRect().top };+ };/** Near the top of loaded history: fetch the previous window (loading/error states gate re-triggering; the retry row is click-driven). */const maybeLoadOlder = (el: HTMLDivElement) => {@@ -302,6 +317,7 @@ export function MessageStream({clientHeight: el.clientHeight,});maybeLoadOlder(el);+ recordAnchor(el);syncJump();};@@ -333,8 +349,9 @@ export function MessageStream({useLayoutEffect(() => {const el = scrollRef.current;// Prepend scroll anchoring: when older windows land ABOVE the viewport, keep the- // message the user was reading exactly where it was by offsetting scrollTop by the- // content growth (same pre-paint timing as the stick snap, so nothing flashes).+ // message the user was reading exactly where it was by moving scrollTop by however far+ // the recorded prompt was displaced (same pre-paint timing as the stick snap, so+ // nothing flashes); the content growth stands in when that prompt is gone.// Keyed on the prepend count — ordinary streaming growth at the bottom must not// shift the view. lastHeightRef is refreshed every commit, so at the prepend commit// it still holds the pre-prepend height. Skipped while the snap below owns the@@ -342,11 +359,20 @@ export function MessageStream({// anchored like any other, since nothing snaps it.const prepended = older?.prependedCount ?? 0;if (el && prepended > lastPrependedRef.current && !follow.snaps && !returningRef.current) {- el.scrollTop += el.scrollHeight - lastHeightRef.current;+ const a = anchorRef.current;+ const node =+ a === null+ ? null+ : el.querySelector<HTMLElement>(`[data-outline-anchor="${CSS.escape(a.id)}"]`);+ el.scrollTop +=+ a !== null && node !== null+ ? node.getBoundingClientRect().top - a.top+ : el.scrollHeight - lastHeightRef.current;}lastPrependedRef.current = prepended;if (el) lastHeightRef.current = el.scrollHeight;if (el && follow.snaps && !returningRef.current) stickToBottom(el, follow);+ if (el) recordAnchor(el);syncJump();// syncJump is recreated per render; the effect intentionally keys on stream growth only.// eslint-disable-next-line react-hooks/exhaustive-deps@@ -453,9 +479,12 @@ export function MessageStream({{/* Top-of-history affordance: spinner while the previous window loads, a click-to-retryrow after a failure, and — once at least one window was backfilled — a quietbeginning-of-conversation marker when there is nothing older. Idle-with-more shows- nothing: scrolling near the top triggers the fetch by itself. */}- {older && items.length > 0 && (- <div className="flex justify-center pb-2">+ nothing — scrolling near the top triggers the fetch by itself — but the row keeps+ its height the moment there IS history above: a spinner that took space only+ while spinning pushed the transcript down by its own height, and the prepend's+ anchoring could not give that back. */}+ {older && items.length > 0 && (older.hasMore || older.prependedCount > 0) && (+ <div className="flex h-7 items-center justify-center">{older.loading ? (<span className="flex items-center gap-2 py-1 text-xs text-gray-400 dark:text-gray-500"><Spinner size="sm" label={S.common.loading} />