Files
chatkit/test/browser-scroll.mjs
CatoandClaude b53f8e615a fix(thread): following never scrolls the page up, and --ck-follow-gap (#88)
On bitbaum /hire/ at 390x844 the contact box (a ChatThread, a receipt link
and the Composer) sits mid-page and the document owns the scroll. The
reader's first message pinned the end of the thread to the bottom of the
viewport, which scrolled the page UP by about 300px and pushed the composer
they were typing in below the fold.

What a consumer gets:
- When the document owns the scroll, following only moves the page down:
  with the end of the thread already on screen, nothing moves. A thread or
  panel that scrolls itself is unchanged, and the jump button still goes to
  the latest turn in either direction, because the reader asked.
- --ck-follow-gap (a length, default 0) on the thread's wrapper or any
  ancestor leaves that much room under the latest turn when the page
  follows, so a composer under the thread stays in view. The browser
  resolves it (rem, em, px, calc); unset, negative or invalid is 0.
- While the reader has sent nothing on a page, nothing moves, as before.

How it is checked: test/browser-scroll.mjs gains a mid-page fixture
(demo/scroll.html?owner=page&greeting&below) at 390 and 1280px. With the
composer mid-screen the first message does not scroll the page up and the
composer stays on screen; as the thread grows past the foot of the screen
the page follows and leaves the end at 0px, 10rem, 6em, 90px and (invalid)
0px above the bottom of the viewport, within 2px. Both checks fail on the
previous code; every existing scroll case passes unchanged.

Claude-Session: https://claude.ai/code/session_019MDtmsSWTTpVpe4wh3v1sb

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-12 10:30:35 +01:00

402 lines
17 KiB
JavaScript

import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import { extname, join, normalize } from "node:path";
import { fileURLToPath } from "node:url";
import { chromium } from "playwright";
import assert from "node:assert/strict";
const root = fileURLToPath(new URL("..", import.meta.url));
const server = createServer(async (req, res) => {
const path = normalize(join(root, new URL(req.url, "http://localhost").pathname));
if (!path.startsWith(root)) return res.writeHead(403).end();
// Read before the head is written: a missing file (or a directory) answers
// 404 instead of throwing "headers already sent" and taking the run down.
let body;
try {
body = await readFile(path);
} catch {
return res.writeHead(404).end();
}
res
.writeHead(200, {
"content-type":
{ ".html": "text/html", ".js": "text/javascript", ".css": "text/css" }[extname(path)] ??
"application/octet-stream",
})
.end(body);
}).listen(0);
const browser = await chromium.launch(
process.env.CHROMIUM_PATH ? { executablePath: process.env.CHROMIUM_PATH } : {},
);
try {
for (const width of [390, 1280])
for (const owner of ["page", "panel", "ancestor"]) {
const page = await browser.newPage({
viewport: { width, height: 844 },
hasTouch: width === 390,
isMobile: width === 390,
});
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.goto(`http://localhost:${server.address().port}/demo/scroll.html?owner=${owner}`);
await page.waitForSelector(".ck-live");
await page.waitForTimeout(400);
const position = () =>
page.evaluate((mode) => {
const el =
mode === "page"
? document.scrollingElement
: mode === "panel"
? document.querySelector(".ck-thread")
: document.querySelector("#fixture-owner");
return { top: el.scrollTop, height: el.scrollHeight, client: el.clientHeight };
}, owner);
const start = await position();
assert.ok(start.top > 100, `${owner} ${width}: starts at latest turn`);
await page.mouse.move(width / 2, 400);
await page.mouse.wheel(0, -450);
await page.waitForTimeout(150);
const reading = await position();
assert.ok(reading.top < start.top - 200, `${owner} ${width}: can scroll upward`);
await page.waitForTimeout(700);
assert.ok(
Math.abs((await position()).top - reading.top) < 3,
`${owner} ${width}: status ticks must not steal reading position`,
);
await page.evaluate(() => document.querySelector("#assistant-turn").click());
await page.waitForTimeout(350);
assert.ok(
Math.abs((await position()).top - reading.top) < 3,
`${owner} ${width}: completed assistant turn must not steal reading position`,
);
await page.setViewportSize({ width, height: 760 });
await page.waitForTimeout(300);
assert.ok(
(await position()).top < start.top - 150,
`${owner} ${width}: resize respects reading`,
);
// Sending a new question is an explicit request to follow the new reply.
await page.evaluate(() => document.querySelector("#user-turn").click());
await page.waitForTimeout(350);
const sent = await position();
assert.ok(
sent.top > reading.top + 200,
`${owner} ${width}: own new question resumes following`,
);
await page.mouse.wheel(0, -25);
await page.waitForTimeout(500);
assert.ok(
(await position()).top < sent.top - 10,
`${owner} ${width}: even a small upward gesture pauses following`,
);
await page.evaluate(() => document.querySelector(".ck-jump").click());
await page.waitForTimeout(650);
const jumped = await position();
assert.ok(
jumped.top > (await position()).top - 3 && jumped.top > reading.top + 200,
`${owner} ${width}: return-to-latest works`,
);
if (width === 390) {
const cdp = await page.context().newCDPSession(page);
await cdp.send("Input.dispatchTouchEvent", {
type: "touchStart",
touchPoints: [{ x: width / 2, y: 180 }],
});
for (let y = 210; y <= 570; y += 30) {
await cdp.send("Input.dispatchTouchEvent", {
type: "touchMove",
touchPoints: [{ x: width / 2, y }],
});
await page.waitForTimeout(25);
}
await cdp.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] });
await page.waitForTimeout(450);
assert.ok(
(await position()).top < jumped.top - 100,
`${owner}: upward touch gesture remains free while statuses change (${jumped.top} -> ${(await position()).top})`,
);
await cdp.detach();
}
await page.locator(".ck-input").fill("A pending synthetic question.");
await page.locator(".ck-input").press("Enter");
await page.waitForFunction(
() => document.getElementById("fixture-sending").textContent === "true",
);
await page.mouse.move(width / 2, 400);
await page.mouse.wheel(0, -420);
await page.waitForTimeout(400);
const pendingReading = await position();
await page.evaluate(() => document.getElementById("finish-send").click());
await page.waitForFunction(() => document.querySelector(".ck-input").value === "");
await page.waitForTimeout(400);
assert.ok(
Math.abs((await position()).top - pendingReading.top) < 4,
`${owner} ${width}: reply completion and focused draft clear preserve reading`,
);
assert.deepEqual(errors, [], `${owner} ${width}: no browser errors`);
await page.close();
console.log(
`PASS ${owner} ${width}: streaming, completed turn, resize, own send and small upward gesture`,
);
}
// A contact box at the foot of a long page (bitbaum /hire/ and /builders/,
// 2026-11-12). The thread holds one greeting and the reader has sent
// nothing, so the document owns the scroll and there is nothing to follow:
// the page must open at its top, stay where the reader puts it, and offer no
// jump button. The reader's first message starts the following.
for (const width of [390, 1280]) {
const page = await browser.newPage({ viewport: { width, height: 844 } });
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.goto(
`http://localhost:${server.address().port}/demo/scroll.html?owner=page&greeting`,
);
await page.waitForSelector(".ck-thread");
await page.waitForTimeout(400);
const top = () => page.evaluate(() => document.scrollingElement.scrollTop);
const jump = () => page.evaluate(() => !!document.querySelector(".ck-jump"));
assert.equal(await top(), 0, `greeting ${width}: the page opens at its top`);
await page.setViewportSize({ width, height: 760 });
await page.waitForTimeout(300);
assert.equal(await top(), 0, `greeting ${width}: a resize does not take the page`);
await page.mouse.move(width / 2, 400);
await page.mouse.wheel(0, 900);
await page.waitForTimeout(200);
const reading = await top();
assert.ok(reading > 600, `greeting ${width}: the reader scrolls the page (${reading})`);
await page.mouse.wheel(0, -300);
await page.waitForTimeout(300);
assert.ok(Math.abs((await top()) - (reading - 300)) < 4, `greeting ${width}: and back up`);
assert.ok(!(await jump()), `greeting ${width}: no jump button before the reader has written`);
await page.evaluate(() => document.querySelector("#user-turn").click());
await page.waitForTimeout(350);
assert.ok(
(await top()) > 2000,
`greeting ${width}: the reader's first message is followed (${await top()})`,
);
assert.deepEqual(errors, [], `greeting ${width}: no browser errors`);
await page.close();
console.log(`PASS greeting ${width}: a greeting on a page leaves the page alone`);
}
// The contact box mid-page (bitbaum /hire/, 2026-11-12): page above it, the
// composer under the thread, more page under the composer. The reader looks
// at the box with the thread's end well above the foot of the screen and
// sends their first message. Following used to align the thread's end with
// the bottom of the viewport, which scrolled the page UP by about 300px and
// pushed the composer they were typing in below the fold. Following may
// only bring a new turn INTO view, and `--ck-follow-gap` keeps room for
// what the host puts under the thread.
for (const width of [390, 1280]) {
const page = await browser.newPage({
viewport: { width, height: 844 },
hasTouch: width === 390,
isMobile: width === 390,
});
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.goto(
`http://localhost:${server.address().port}/demo/scroll.html?owner=page&greeting&below`,
);
await page.waitForSelector(".ck-thread");
await page.waitForTimeout(400);
const top = () => page.evaluate(() => document.scrollingElement.scrollTop);
const layout = () =>
page.evaluate(() => {
const end = document.querySelector(".ck-thread-inner > :last-child");
const composer = document.querySelector(".ck-composer");
return {
top: document.scrollingElement.scrollTop,
end: end.getBoundingClientRect().bottom,
composerTop: composer.getBoundingClientRect().top,
composerBottom: composer.getBoundingClientRect().bottom,
viewport: window.innerHeight,
};
});
// The composer in the middle of the screen, as a reader who has scrolled
// to the box and is about to write.
await page.evaluate(() => {
const box = document.querySelector(".ck-composer").getBoundingClientRect();
window.scrollBy({
top: box.top + box.height / 2 - window.innerHeight / 2,
behavior: "instant",
});
});
await page.waitForTimeout(200);
const before = await layout();
assert.ok(before.top > 2000, `mid-page ${width}: the box is far down the page`);
assert.ok(
before.end < before.viewport - 100,
`mid-page ${width}: the thread's end is above the foot of the screen (${before.end})`,
);
await page.locator(".ck-input").fill("A first synthetic question.");
await page.locator(".ck-input").press("Enter");
await page.waitForFunction(
() => document.getElementById("fixture-sending").textContent === "true",
);
await page.waitForTimeout(350);
const sent = await layout();
assert.ok(
sent.top >= before.top - 1,
`mid-page ${width}: the first message does not scroll the page up (${before.top} -> ${sent.top})`,
);
assert.ok(
sent.composerBottom <= sent.viewport,
`mid-page ${width}: the composer stays on screen (${sent.composerBottom} of ${sent.viewport})`,
);
// The thread grows past the foot of the screen: the page follows it down
// and stops with the thread's end at the bottom of the viewport, or the
// host's gap above it.
const grow = async (label, gap) => {
const start = await top();
for (let i = 0; i < 40; i++) {
await page.evaluate(() => document.querySelector("#assistant-turn").click());
await page.waitForTimeout(60);
if ((await top()) > start + 150) break;
}
await page.waitForTimeout(250);
const after = await layout();
assert.ok(
after.top > start + 100,
`${label} ${width}: the page followed (${start} -> ${after.top})`,
);
const distance = after.viewport - after.end;
assert.ok(
Math.abs(distance - gap) <= 2,
`${label} ${width}: the thread's end sits ${gap}px above the foot of the screen (${distance})`,
);
};
await grow("no gap", 0);
await page.evaluate(() =>
document.querySelector(".ck-thread-wrap").style.setProperty("--ck-follow-gap", "10rem"),
);
await grow("--ck-follow-gap: 10rem", 160);
await page.evaluate(() => {
const wrap = document.querySelector(".ck-thread-wrap");
wrap.style.fontSize = "20px";
wrap.style.setProperty("--ck-follow-gap", "6em");
});
await grow("--ck-follow-gap: 6em", 120);
await page.evaluate(() =>
document.querySelector(".ck-thread-wrap").style.setProperty("--ck-follow-gap", "90px"),
);
await grow("--ck-follow-gap: 90px", 90);
await page.evaluate(() =>
document.querySelector(".ck-thread-wrap").style.setProperty("--ck-follow-gap", "nonsense"),
);
await grow("--ck-follow-gap: invalid", 0);
assert.deepEqual(errors, [], `mid-page ${width}: no browser errors`);
await page.close();
console.log(
`PASS mid-page ${width}: the first message keeps the composer in view; --ck-follow-gap holds`,
);
}
// ChatScreen on a phone, driven by a finger (OrangeCat's Diplodoctor chat,
// 2026-11-01). Read up, come back down by hand: a finger rocks back a
// pixel or two as it lifts, and that last move used to read as "scrolling
// up", so the jump button stayed on screen at the bottom with nowhere to
// go. Then the button itself, TAPPED, not clicked from script.
{
const page = await browser.newPage({
viewport: { width: 390, height: 780 },
hasTouch: true,
isMobile: true,
});
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.goto(`http://localhost:${server.address().port}/demo/screen.html`);
await page.waitForSelector(".ck-screen .ck-thread");
await page.waitForTimeout(400);
const state = () =>
page.evaluate(() => {
const t = document.querySelector(".ck-screen .ck-thread");
return {
gap: Math.round(t.scrollHeight - t.scrollTop - t.clientHeight),
jump: !!document.querySelector(".ck-screen .ck-jump"),
};
});
const cdp = await page.context().newCDPSession(page);
const swipe = async (from, to, wobble = 0) => {
await cdp.send("Input.dispatchTouchEvent", {
type: "touchStart",
touchPoints: [{ x: 120, y: from }],
});
const step = from < to ? 30 : -30;
let y;
for (y = from + step; step > 0 ? y <= to : y >= to; y += step) {
await cdp.send("Input.dispatchTouchEvent", {
type: "touchMove",
touchPoints: [{ x: 120, y }],
});
await page.waitForTimeout(16);
}
if (wobble)
await cdp.send("Input.dispatchTouchEvent", {
type: "touchMove",
touchPoints: [{ x: 120, y: y - step + wobble }],
});
await cdp.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] });
await page.waitForTimeout(500);
};
await swipe(200, 560);
await swipe(200, 560);
const up = await state();
assert.ok(up.gap > 300 && up.jump, `screen: reading up shows the jump button (${up.gap})`);
for (let i = 0; i < 12 && (await state()).gap > 0; i++) await swipe(500, 150, 2);
const down = await state();
assert.ok(down.gap <= 16, `screen: a hand scroll reaches the bottom (${down.gap})`);
assert.ok(!down.jump, "screen: back at the bottom by hand, the jump button is gone");
await swipe(200, 560);
const box = await page.locator(".ck-screen .ck-jump").boundingBox();
assert.ok(box, "screen: reading up again shows the jump button");
await page.touchscreen.tap(box.x + box.width / 2, box.y + box.height / 2);
await page.waitForTimeout(900);
const tapped = await state();
assert.ok(
tapped.gap <= 2 && !tapped.jump,
`screen: a tap on it lands at the latest message (${tapped.gap})`,
);
await cdp.detach();
assert.deepEqual(errors, [], "screen: no browser errors");
await page.close();
console.log("PASS screen 390: hand scroll back down hides the jump button; a tap on it jumps");
}
// Reproduce DOM implementations where document.scrollingElement is absent.
// Start with a real thread scroll owner, then remove its scrollability so
// the hook must safely replace a stale owner with no document fallback.
{
const page = await browser.newPage({ viewport: { width: 390, height: 844 } });
const errors = [];
page.on("pageerror", (error) => errors.push(error.message));
await page.goto(
`http://localhost:${server.address().port}/demo/scroll.html?owner=panel&null-root`,
);
await page.waitForSelector(".ck-live");
await page.waitForTimeout(350);
await page.evaluate(() => {
for (const el of [
document.querySelector(".ck-thread"),
document.querySelector("#fixture-owner"),
document.body,
document.documentElement,
]) {
if (el) el.style.overflowY = "visible";
}
});
await page.waitForTimeout(500);
assert.deepEqual(
errors,
[],
"missing document scrolling element does not crash after layout changes",
);
await page.close();
console.log("PASS missing document scrolling element after a prior thread scroll owner");
}
} finally {
await browser.close();
server.close();
}