Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
test(web): characterize message scroll behavior (#671)
Generd1bc14798d3c
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjsindex 76abdda4b..b72acf645 100644--- a/scripts/ci/e2e-shards.mjs+++ b/scripts/ci/e2e-shards.mjs@@ -66,6 +66,7 @@ export const SPEC_SECONDS = {"53-mobile-inbox-surface.spec.ts": 45,"54-authenticated-context-menu-policy.spec.ts": 55,"54-blog-multizone.spec.ts": 60,+ "55-message-scroll-characterization.spec.ts": 180,}function walk(directory) {diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.tsindex 82e733cf8..fc275ddf6 100644--- a/scripts/ci/e2e-shards.test.ts+++ b/scripts/ci/e2e-shards.test.ts@@ -70,7 +70,7 @@ describe("planE2eShards", () => {expect(first).toHaveLength(E2E_SHARD_COUNT)expect([...assigned].sort()).toEqual(specs)expect(new Set(assigned).size).toBe(specs.length)- expect(totals.sort((left, right) => left - right)).toEqual([514, 516, 516, 517, 517])+ expect(totals.sort((left, right) => left - right)).toEqual([550, 551, 551, 553, 555])expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)})diff --git a/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts b/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.tsnew file mode 100644index 000000000..a6a46ddd6--- /dev/null+++ b/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts@@ -0,0 +1,669 @@+import type { Locator, Page, Route, TestInfo } from "@playwright/test"+import { test, expect, sessionCookie } from "./_fixtures/community-fixture"+import { composerEditable, gotoAfterUserWsAuth, sendMessage } from "./_fixtures/actions"+import {+ communityFrameEvents,+ proxyCommunityWebSockets,+} from "./_fixtures/community-ws-proxy"+import { seedChannel, seedJoinServer, seedMessage, seedServer } from "./_fixtures/seed"+import {+ abortScrollTrace,+ attachScrollTrace,+ beginScrollTraceAnalysis,+ createScrollTraceIdentity,+ endScrollTraceAnalysis,+ finishScrollTrace,+ installScrollTrace,+ installScrollTraceInCurrentDocument,+ markScrollTrace,+ scrollTraceSelfTest,+ startScrollTrace,+ type ScrollTraceResult,+} from "./_fixtures/scroll-trace"+import { tid } from "./_fixtures/testids"+import { WEB_URL } from "./_setup/paths"++const VIEWPORT = { width: 1280, height: 800 }++type HeldRequest = {+ matched: Promise<URL>+ release: () => void+ dispose: () => Promise<void>+}++async function holdNextRequest(+ page: Page,+ pattern: string,+ predicate: (url: URL) => boolean,+): Promise<HeldRequest> {+ let resolveMatched!: (url: URL) => void+ let release!: () => void+ let consumed = false+ let timeout: ReturnType<typeof setTimeout> | undefined+ const matched = new Promise<URL>((resolveValue, reject) => {+ resolveMatched = (url) => {+ if (timeout) clearTimeout(timeout)+ resolveValue(url)+ }+ timeout = setTimeout(() => reject(new Error(`held request did not match ${pattern}`)), 20_000)+ })+ const gate = new Promise<void>((resolveValue) => { release = resolveValue })+ const handler = async (route: Route) => {+ const url = new URL(route.request().url())+ if (!consumed && predicate(url)) {+ consumed = true+ resolveMatched(url)+ await gate+ }+ await route.continue()+ }+ await page.route(pattern, handler)+ return {+ matched,+ release,+ dispose: async () => {+ if (timeout) clearTimeout(timeout)+ release()+ await page.unroute(pattern, handler)+ },+ }+}++function profileContent(index: number): string {+ const shape = index % 8+ if (shape === 0) return `short row ${index}`+ if (shape === 1) return Array.from({ length: 4 }, (_, line) => `row ${index} line ${line}`).join("\n")+ if (shape === 2) return Array.from({ length: 12 }, (_, line) => `row ${index} variable line ${line} ${"x".repeat(line * 2)}`).join("\n")+ if (shape === 3) return `long-token-${"characterization".repeat(18)}-${index}`+ if (shape === 4) return `- list ${index}\n- second item ${"wide ".repeat(12)}\n- third item`+ if (shape === 5) return `> quote ${index}\n> ${"quoted content ".repeat(15)}`+ if (shape === 6) return `\`\`\`ts\nconst row${index} = ${JSON.stringify("code ".repeat(18))}\n\`\`\``+ return `**bold ${index}** ${"wrapping markdown ".repeat(22)}`+}++function estimatePlainMessage(content: string): number {+ return 24 + Math.min(Math.max(1, Math.ceil(content.length / 55)) * 20, 400)+}++async function seedProfile(+ channelId: string,+ count: number,+ imageAtTail = false,+ authors: "rotate" | "alice" = "rotate",+ checkpointAt?: number,+): Promise<{ ids: string[]; estimates: Record<string, number> }> {+ const ids: string[] = []+ const estimates: Record<string, number> = {}+ for (let index = 0; index < count; index += 1) {+ const content = imageAtTail && index === count - 1+ ? `async image row ${index}\n`+ : profileContent(index)+ const afterCheckpoint = checkpointAt !== undefined && index > checkpointAt+ const author = afterCheckpoint+ ? index % 2 === 0 ? "bob" : "carol"+ : authors === "alice"+ ? "alice"+ : index % 3 === 0 ? "alice" : index % 3 === 1 ? "bob" : "carol"+ const id = await seedMessage(author, channelId, content)+ ids.push(id)+ estimates[id] = estimatePlainMessage(content)+ if (index === checkpointAt) await setReadCheckpoint(channelId, id)+ }+ return { ids, estimates }+}++async function setReadCheckpoint(channelId: string, messageId: string): Promise<void> {+ const response = await fetch(`${WEB_URL}/api/community/channels/${channelId}/read`, {+ method: "PUT",+ headers: {+ Cookie: sessionCookie("alice"),+ "Content-Type": "application/json",+ Origin: WEB_URL,+ },+ body: JSON.stringify({ lastReadMessageId: messageId }),+ })+ expect(response.ok).toBe(true)+}++function identity(channelId: string) {+ return createScrollTraceIdentity({+ account: "alice",+ channel: channelId,+ viewport: { ...VIEWPORT, dpr: 1 },+ })+}++async function finishAndAttach(page: Page, testInfo: TestInfo): Promise<ScrollTraceResult> {+ await markScrollTrace(page, "final-stimulus")+ const result = await finishScrollTrace(page)+ await attachScrollTrace(testInfo, result)+ return result+}++async function establishScrollDistancePrecondition(+ scroller: Locator,+ label: string,+ targetDistanceToEnd: number,+): Promise<{ scrollTop: number; scrollHeight: number; clientHeight: number; distanceToEnd: number }> {+ const readGeometry = () => scroller.evaluate((element) => ({+ scrollTop: element.scrollTop,+ scrollHeight: element.scrollHeight,+ clientHeight: element.clientHeight,+ distanceToEnd: Math.max(0, element.scrollHeight - element.clientHeight - element.scrollTop),+ })).then((geometry) => ({+ ...geometry,+ targetDistanceToEnd,+ atTarget: Math.abs(geometry.distanceToEnd - targetDistanceToEnd) <= 1,+ }))+ const driveToTarget = async () => {+ const geometry = await readGeometry()+ if (geometry.atTarget) return geometry+ await scroller.evaluate((element, targetDistance) => {+ element.scrollTop = Math.max(0, element.scrollHeight - element.clientHeight - targetDistance)+ element.dispatchEvent(new Event("scroll"))+ }, targetDistanceToEnd)+ return readGeometry()+ }+ await scroller.evaluate((element, targetDistance) => {+ element.scrollTop = Math.max(0, element.scrollHeight - element.clientHeight - targetDistance)+ element.dispatchEvent(new Event("scroll"))+ }, targetDistanceToEnd)+ await expect.poll(driveToTarget, {+ timeout: 20_000,+ message: `${label}: scroller must reach ${targetDistanceToEnd}px from end before the stimulus`,+ }).toMatchObject({ atTarget: true })+ await scroller.evaluate(() => new Promise<void>((resolveValue) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolveValue()))+ }))+ await expect.poll(driveToTarget, {+ timeout: 20_000,+ message: `${label}: ${targetDistanceToEnd}px distance must survive two committed RAFs`,+ }).toMatchObject({ atTarget: true })+ await scroller.evaluate(() => new Promise<void>((resolveValue) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolveValue()))+ }))+ await expect.poll(readGeometry, {+ timeout: 20_000,+ message: `${label}: ${targetDistanceToEnd}px distance must remain stable without another write`,+ }).toMatchObject({ atTarget: true })+ const { atTarget: _atTarget, targetDistanceToEnd: _target, ...geometry } = await readGeometry()+ return geometry+}++async function establishMidHistoryPrecondition(+ scroller: Locator,+): Promise<{ scrollTop: number; scrollHeight: number; clientHeight: number; distanceToEnd: number }> {+ const readGeometry = () => scroller.evaluate((element) => ({+ scrollTop: element.scrollTop,+ scrollHeight: element.scrollHeight,+ clientHeight: element.clientHeight,+ distanceToEnd: Math.max(0, element.scrollHeight - element.clientHeight - element.scrollTop),+ }))+ await scroller.evaluate((element) => {+ element.scrollTop = Math.max(0, (element.scrollHeight - element.clientHeight) / 2)+ element.dispatchEvent(new Event("scroll"))+ })+ await expect.poll(async () => {+ const geometry = await readGeometry()+ return {+ ...geometry,+ insideHistory: geometry.scrollTop > 300 && geometry.distanceToEnd > 300,+ }+ }, {+ timeout: 20_000,+ message: "remote-mid-history: scroller must be stably away from both boundaries",+ }).toMatchObject({ insideHistory: true })+ await scroller.evaluate(() => new Promise<void>((resolveValue) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolveValue()))+ }))+ const before = await readGeometry()+ await scroller.evaluate(() => new Promise<void>((resolveValue) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolveValue()))+ }))+ await expect.poll(async () => {+ const geometry = await readGeometry()+ return {+ ...geometry,+ stable: Math.abs(geometry.scrollTop - before.scrollTop) <= 1+ && geometry.scrollTop > 300+ && geometry.distanceToEnd > 300,+ }+ }, {+ timeout: 20_000,+ message: "remote-mid-history: actual geometry must remain stable across committed RAFs",+ }).toMatchObject({ stable: true })+ return readGeometry()+}++function messageCreateCount(+ frames: Awaited<ReturnType<typeof proxyCommunityWebSockets>>["frames"],+ channelId: string,+ body: string,+): number {+ return frames.filter((frame) => communityFrameEvents(frame).some((event) =>+ event.type === "community:message.create"+ && event.channelId === channelId+ && event.message?.content?.includes(body))).length+}++test.describe.serial("message scroll characterization", () => {+ let serverId: string+ let coldChannelId: string+ let loadingChannelId: string+ let upwardChannelId: string+ let composerChannelId: string+ let loadingProfile: Awaited<ReturnType<typeof seedProfile>>+ let upwardProfile: Awaited<ReturnType<typeof seedProfile>>+ let composerProfile: Awaited<ReturnType<typeof seedProfile>>++ test.beforeAll(async () => {+ test.setTimeout(240_000)+ const stamp = Date.now()+ serverId = await seedServer("alice", `Scroll characterization ${stamp}`)+ await seedJoinServer("alice", "bob", serverId)+ await seedJoinServer("alice", "carol", serverId)+ coldChannelId = await seedChannel("alice", serverId, `scroll-cold-${stamp}`)+ loadingChannelId = await seedChannel("alice", serverId, `scroll-loading-${stamp}`)+ upwardChannelId = await seedChannel("alice", serverId, `scroll-upward-${stamp}`)+ composerChannelId = await seedChannel("alice", serverId, `scroll-composer-${stamp}`)+ loadingProfile = await seedProfile(loadingChannelId, 130, false, "rotate", 64)+ upwardProfile = await seedProfile(upwardChannelId, 72, false, "rotate", 23)+ composerProfile = await seedProfile(composerChannelId, 36, true, "alice")+ })++ test("cold and warm loading, older prepend, and jump-to-present remain observable", async ({ asUser }, testInfo) => {+ test.setTimeout(180_000)+ const alice = await asUser("alice")+ await alice.page.setViewportSize(VIEWPORT)+ await installScrollTrace(alice.page)+ const initialMessages = await holdNextRequest(+ alice.page,+ `**/api/community/channels/${coldChannelId}/messages**`,+ () => true,+ )+ const image = await holdNextRequest(+ alice.page,+ "**/icon-512.png?scroll-trace=1",+ () => true,+ )+ await alice.page.goto(`/c/channels/${serverId}/${coldChannelId}`, { waitUntil: "commit" })+ const initialUrl = await initialMessages.matched+ expect(initialUrl.searchParams.has("anchor")).toBe(false)+ const scroller = alice.page.getByTestId(tid.messageScroller)+ await expect(scroller.locator('[data-slot="skeleton"]').first()).toBeVisible({ timeout: 20_000 })+ const selfTest = await scrollTraceSelfTest(alice.page)+ expect(selfTest).toMatchObject({+ getterValue: 7,+ methodValue: 8,+ setterError: "RangeError",+ methodError: "RangeError",+ receiverPreserved: true,+ restored: true,+ unsupportedUntouched: true,+ })+ await startScrollTrace(alice.page, {+ scenario: "cold-load-and-async-row",+ identity: identity(coldChannelId),+ })+ await beginScrollTraceAnalysis(alice.page, "cold-load-and-async-row", {+ dataTransitionSource: "initial-cold",+ })+ await markScrollTrace(alice.page, "cold-request-held", { dataTransitionSource: "initial-cold" })+ const coldProfile = await seedProfile(coldChannelId, 12, true, "alice")+ initialMessages.release()+ await image.matched+ await expect(alice.page.getByTestId(tid.message(coldProfile.ids.at(-1)!))).toBeVisible({ timeout: 30_000 })+ await markScrollTrace(alice.page, "async-image-release", {+ detail: { position: "tail", asset: "local-fixture" },+ })+ image.release()+ await expect(alice.page.getByTestId(tid.message(coldProfile.ids.at(-1)!)).locator("img")).toBeVisible()+ await endScrollTraceAnalysis(alice.page, "cold-load-and-async-row")+ const cold = await finishAndAttach(alice.page, testInfo)+ expect(cold.frames.some((frame) => frame.loaders.top.mounted || frame.rows.length === 0)).toBe(true)+ await initialMessages.dispose()+ await image.dispose()++ await installScrollTraceInCurrentDocument(alice.page)+ await alice.page.getByTestId(tid.channelRow(loadingChannelId)).click()+ await alice.page.waitForURL(new RegExp(loadingChannelId), { waitUntil: "commit" })+ await expect(alice.page.getByTestId(tid.messageScroller)).toBeVisible()+ const warmRequest = await holdNextRequest(+ alice.page,+ `**/api/community/channels/${coldChannelId}/messages**`,+ () => true,+ )+ await alice.page.getByTestId(tid.channelRow(coldChannelId)).click()+ await alice.page.waitForURL(new RegExp(coldChannelId), { waitUntil: "commit" })+ await warmRequest.matched+ await expect(alice.page.getByTestId(tid.message(coldProfile.ids.at(-1)!))).toBeVisible({ timeout: 20_000 })+ await startScrollTrace(alice.page, {+ scenario: "warm-cache-revalidation",+ identity: identity(coldChannelId),+ estimatedSizes: coldProfile.estimates,+ })+ await beginScrollTraceAnalysis(alice.page, "warm-cache-revalidation", {+ dataTransitionSource: "initial-cache",+ })+ await markScrollTrace(alice.page, "cached-rows-painted", {+ dataTransitionSource: "initial-cache",+ detail: { renderedBeforeRelease: true },+ })+ warmRequest.release()+ await endScrollTraceAnalysis(alice.page, "warm-cache-revalidation")+ await finishAndAttach(alice.page, testInfo)+ await warmRequest.dispose()++ const anchored = await asUser("alice")+ await anchored.page.setViewportSize(VIEWPORT)+ await installScrollTrace(anchored.page)+ await anchored.page.goto(`/c/channels/${serverId}/${loadingChannelId}`, { waitUntil: "commit" })+ await expect(anchored.page.getByTestId(tid.newDivider)).toBeVisible({ timeout: 30_000 })+ const older = await holdNextRequest(+ anchored.page,+ `**/api/community/channels/${loadingChannelId}/messages**`,+ (url) => url.searchParams.has("cursor"),+ )+ await startScrollTrace(anchored.page, {+ scenario: "older-loading-prepend",+ identity: identity(loadingChannelId),+ estimatedSizes: loadingProfile.estimates,+ })+ await beginScrollTraceAnalysis(anchored.page, "older-loading-prepend", {+ dataTransitionSource: "older-page",+ commandDirection: "backward",+ })+ await markScrollTrace(anchored.page, "stimulus:older-boundary", { dataTransitionSource: "older-page" })+ await anchored.page.getByTestId(tid.messageScroller).evaluate((element) => {+ element.scrollTop = 0+ element.dispatchEvent(new Event("scroll"))+ })+ await older.matched+ await expect(anchored.page.getByText("Loading older messages…", { exact: true })).toBeVisible()+ older.release()+ await expect(anchored.page.getByText("Loading older messages…", { exact: true })).toHaveCount(0)+ await endScrollTraceAnalysis(anchored.page, "older-loading-prepend")+ const olderTrace = await finishAndAttach(anchored.page, testInfo)+ expect(olderTrace.marks.filter((mark) =>+ mark.name === "stimulus:older-boundary"+ && mark.dataTransitionSource === "older-page")).toHaveLength(1)+ await older.dispose()++ await installScrollTraceInCurrentDocument(anchored.page)+ const present = anchored.page.getByTestId(tid.scrollToPresent)+ await expect(present).toBeVisible({ timeout: 30_000 })+ let newestGets = 0+ anchored.page.on("request", (request) => {+ const url = new URL(request.url())+ if (+ request.method() === "GET"+ && url.pathname === `/api/community/channels/${loadingChannelId}/messages`+ && url.search === ""+ ) newestGets += 1+ })+ const newest = await holdNextRequest(+ anchored.page,+ `**/api/community/channels/${loadingChannelId}/messages**`,+ (url) => url.search === "",+ )+ await startScrollTrace(anchored.page, {+ scenario: "newer-loading-present",+ identity: identity(loadingChannelId),+ estimatedSizes: loadingProfile.estimates,+ })+ await beginScrollTraceAnalysis(anchored.page, "newer-loading-present", {+ dataTransitionSource: "newer-page",+ commandDirection: "forward",+ })+ await markScrollTrace(anchored.page, "stimulus:jump-present", { dataTransitionSource: "newer-page" })+ await present.click()+ await newest.matched+ newest.release()+ await expect(anchored.page.getByTestId(tid.message(loadingProfile.ids.at(-1)!))).toBeVisible({ timeout: 30_000 })+ await expect(present).toHaveCount(0)+ await endScrollTraceAnalysis(anchored.page, "newer-loading-present")+ await finishAndAttach(anchored.page, testInfo)+ await expect.poll(() => newestGets).toBe(1)+ await anchored.page.waitForTimeout(500)+ expect(newestGets).toBe(1)+ await newest.dispose()+ })++ test("remote receive states and sustained upward input produce diagnostic traces", async ({ asUser }, testInfo) => {+ test.setTimeout(180_000)+ const alice = await asUser("alice")+ await alice.page.setViewportSize(VIEWPORT)+ await installScrollTrace(alice.page)+ const proxy = await proxyCommunityWebSockets(alice.context)+ await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${upwardChannelId}`)+ await expect(alice.page.getByTestId(tid.newDivider)).toBeVisible({ timeout: 30_000 })+ const scroller = alice.page.getByTestId(tid.messageScroller)+ await startScrollTrace(alice.page, {+ scenario: "remote-receive-and-upward-input",+ commandDirection: "backward",+ identity: identity(upwardChannelId),+ estimatedSizes: upwardProfile.estimates,+ })++ await markScrollTrace(alice.page, "stimulus:pin-tail")+ const pinnedPrecondition = await establishScrollDistancePrecondition(scroller, "remote-pinned", 0)+ await markScrollTrace(alice.page, "remote-pinned-precondition", {+ detail: pinnedPrecondition,+ })+ await beginScrollTraceAnalysis(alice.page, "remote-pinned", {+ dataTransitionSource: "overlay-ws",+ })+ const pinnedBody = `remote pinned ${Date.now()}`+ await markScrollTrace(alice.page, "remote-pinned", { dataTransitionSource: "overlay-ws" })+ const pinnedId = await seedMessage("bob", upwardChannelId, pinnedBody)+ await expect(alice.page.getByTestId(tid.message(pinnedId))).toBeVisible({ timeout: 20_000 })+ await expect.poll(() => scroller.evaluate((element) =>+ Math.max(0, element.scrollHeight - element.clientHeight - element.scrollTop))).toBeLessThanOrEqual(1)+ await endScrollTraceAnalysis(alice.page, "remote-pinned")++ await markScrollTrace(alice.page, "stimulus:away-101")+ const awayPrecondition = await establishScrollDistancePrecondition(scroller, "remote-away-101", 101)+ await markScrollTrace(alice.page, "remote-away-precondition", {+ detail: awayPrecondition,+ })+ await beginScrollTraceAnalysis(alice.page, "remote-away-101", {+ dataTransitionSource: "overlay-ws",+ })+ const awayBody = `remote away ${Date.now()}`+ await markScrollTrace(alice.page, "remote-away", { dataTransitionSource: "overlay-ws" })+ await seedMessage("carol", upwardChannelId, awayBody)+ await expect.poll(() => messageCreateCount(proxy.frames, upwardChannelId, awayBody)).toBe(1)+ const awayObservation = await scroller.evaluate((element, pillTestId) => ({+ distanceToEnd: Math.max(0, element.scrollHeight - element.clientHeight - element.scrollTop),+ pillVisible: !!document.querySelector(`[data-testid='${pillTestId}']`),+ }), tid.scrollToPresent)+ await markScrollTrace(alice.page, "remote-away-observed", { detail: awayObservation })+ await endScrollTraceAnalysis(alice.page, "remote-away-101")++ await markScrollTrace(alice.page, "stimulus:mid-history")+ const midHistoryPrecondition = await establishMidHistoryPrecondition(scroller)+ await markScrollTrace(alice.page, "remote-mid-history-precondition", {+ detail: midHistoryPrecondition,+ })+ await beginScrollTraceAnalysis(alice.page, "remote-mid-history-burst", {+ dataTransitionSource: "overlay-ws",+ })+ for (let index = 0; index < 3; index += 1) {+ await markScrollTrace(alice.page, `remote-burst-${index}`, { dataTransitionSource: "overlay-ws" })+ await seedMessage(index % 2 === 0 ? "bob" : "carol", upwardChannelId, `remote burst ${index} ${Date.now()}`)+ }+ await endScrollTraceAnalysis(alice.page, "remote-mid-history-burst")+ await beginScrollTraceAnalysis(alice.page, "remote-during-smooth", {+ dataTransitionSource: "overlay-ws",+ commandDirection: "forward",+ })+ const smoothBody = `remote during smooth ${Date.now()}`+ await markScrollTrace(alice.page, "remote-during-smooth", { dataTransitionSource: "overlay-ws" })+ await scroller.evaluate((element) => element.scrollTo({+ top: element.scrollHeight,+ behavior: "smooth",+ }))+ await seedMessage("bob", upwardChannelId, smoothBody)+ await expect.poll(() => messageCreateCount(proxy.frames, upwardChannelId, smoothBody)).toBe(1)+ await endScrollTraceAnalysis(alice.page, "remote-during-smooth")++ await markScrollTrace(alice.page, "stimulus:reset-tail")+ const upwardPrecondition = await establishScrollDistancePrecondition(scroller, "upward-60x24", 0)+ await markScrollTrace(alice.page, "upward-precondition", { detail: upwardPrecondition })+ const box = await scroller.boundingBox()+ expect(box).not.toBeNull()+ await alice.page.mouse.move(box!.x + box!.width / 2, box!.y + box!.height / 2)+ await beginScrollTraceAnalysis(alice.page, "upward-60x24", {+ dataTransitionSource: "overlay-ws",+ commandDirection: "backward",+ })+ await markScrollTrace(alice.page, "stimulus:upward-60x24")+ const liveAppend = (async () => {+ await alice.page.waitForTimeout(250)+ await markScrollTrace(alice.page, "upward-live-append", { dataTransitionSource: "overlay-ws" })+ return seedMessage("carol", upwardChannelId, `upward live ${Date.now()}`)+ })()+ for (let index = 0; index < 60; index += 1) {+ await alice.page.mouse.wheel(0, -24)+ await alice.page.waitForTimeout(24)+ }+ await liveAppend+ await endScrollTraceAnalysis(alice.page, "upward-60x24")+ const trace = await finishAndAttach(alice.page, testInfo)+ expect(trace.externalEvents.filter((event) => event.type === "wheel")).toHaveLength(60)+ expect(trace.marks.filter((mark) => mark.dataTransitionSource === "overlay-ws").length)+ .toBeGreaterThanOrEqual(7)+ })++ test("manual draft clear and optimistic send stay distinct through viewport changes", async ({ asUser }, testInfo) => {+ test.setTimeout(180_000)+ const alice = await asUser("alice")+ await alice.page.setViewportSize(VIEWPORT)+ await installScrollTrace(alice.page)+ const proxy = await proxyCommunityWebSockets(alice.context)+ let messagePosts = 0+ alice.page.on("request", (request) => {+ if (+ request.method() === "POST"+ && new URL(request.url()).pathname === `/api/community/channels/${composerChannelId}/messages`+ ) messagePosts += 1+ })+ await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${composerChannelId}`)+ const scroller = alice.page.getByTestId(tid.messageScroller)+ const editable = composerEditable(alice.page)+ await expect(editable).toBeVisible()+ await startScrollTrace(alice.page, {+ scenario: "composer-clear-send-and-viewport",+ identity: identity(composerChannelId),+ estimatedSizes: composerProfile.estimates,+ })++ const typeSixLines = async (prefix: string) => {+ await editable.click()+ for (let line = 0; line < 6; line += 1) {+ await editable.pressSequentially(`${prefix} line ${line} ${"content ".repeat(8)}`)+ if (line < 5) await alice.page.keyboard.press("Shift+Enter")+ }+ }+ await markScrollTrace(alice.page, "stimulus:prepare-pinned-draft")+ await typeSixLines("pinned")+ const pinnedDraftPrecondition = await establishScrollDistancePrecondition(+ scroller,+ "manual-delete-pinned",+ 0,+ )+ await markScrollTrace(alice.page, "manual-delete-pinned-precondition", {+ detail: pinnedDraftPrecondition,+ })+ await beginScrollTraceAnalysis(alice.page, "manual-delete-pinned")+ await markScrollTrace(alice.page, "manual-delete-pinned")+ await alice.page.keyboard.press("ControlOrMeta+A")+ await alice.page.keyboard.press("Backspace")+ await expect(alice.page.getByTestId(tid.composerInput)).toHaveText("")+ expect(messagePosts).toBe(0)+ expect(proxy.frames.flatMap(communityFrameEvents).filter((event) =>+ event.type === "community:message.create" && event.channelId === composerChannelId)).toHaveLength(0)+ await endScrollTraceAnalysis(alice.page, "manual-delete-pinned")++ await markScrollTrace(alice.page, "stimulus:prepare-away-draft")+ await typeSixLines("away")+ const awayDraftPrecondition = await establishScrollDistancePrecondition(+ scroller,+ "manual-delete-away",+ 300,+ )+ await markScrollTrace(alice.page, "manual-delete-away-precondition", {+ detail: awayDraftPrecondition,+ })+ await beginScrollTraceAnalysis(alice.page, "manual-delete-away")+ await markScrollTrace(alice.page, "manual-delete-away")+ await alice.page.keyboard.press("ControlOrMeta+A")+ await alice.page.keyboard.press("Backspace")+ await expect(alice.page.getByTestId(tid.composerInput)).toHaveText("")+ expect(messagePosts).toBe(0)+ await endScrollTraceAnalysis(alice.page, "manual-delete-away")++ await markScrollTrace(alice.page, "stimulus:pin-for-send")+ const pinnedSendPrecondition = await establishScrollDistancePrecondition(+ scroller,+ "optimistic-send-pinned",+ 0,+ )+ await markScrollTrace(alice.page, "optimistic-send-pinned-precondition", {+ detail: pinnedSendPrecondition,+ })+ await beginScrollTraceAnalysis(alice.page, "optimistic-send-pinned", {+ dataTransitionSource: "optimistic-send",+ })+ const pinnedSend = `optimistic pinned ${Date.now()}`+ await markScrollTrace(alice.page, "optimistic-pinned", { dataTransitionSource: "optimistic-send" })+ await sendMessage(alice.page, pinnedSend)+ await expect(alice.page.getByText(pinnedSend, { exact: true })).toHaveCount(1)+ await markScrollTrace(alice.page, "post-ack-pinned", { dataTransitionSource: "post-ack" })+ await expect.poll(() => messageCreateCount(proxy.frames, composerChannelId, pinnedSend)).toBe(1)+ await markScrollTrace(alice.page, "ws-dedupe-pinned", { dataTransitionSource: "ws-dedupe" })+ await endScrollTraceAnalysis(alice.page, "optimistic-send-pinned")++ await markScrollTrace(alice.page, "stimulus:send-away")+ const awaySendPrecondition = await establishScrollDistancePrecondition(+ scroller,+ "optimistic-send-away",+ 300,+ )+ await markScrollTrace(alice.page, "optimistic-send-away-precondition", {+ detail: awaySendPrecondition,+ })+ await beginScrollTraceAnalysis(alice.page, "optimistic-send-away", {+ dataTransitionSource: "optimistic-send",+ })+ const awaySend = `optimistic away ${Date.now()}`+ await markScrollTrace(alice.page, "optimistic-away", { dataTransitionSource: "optimistic-send" })+ await sendMessage(alice.page, awaySend)+ await expect(alice.page.getByText(awaySend, { exact: true })).toHaveCount(1)+ await markScrollTrace(alice.page, "post-ack-away", { dataTransitionSource: "post-ack" })+ await expect.poll(() => messageCreateCount(proxy.frames, composerChannelId, awaySend)).toBe(1)+ await markScrollTrace(alice.page, "ws-dedupe-away", { dataTransitionSource: "ws-dedupe" })+ await expect.poll(() => scroller.evaluate((element) =>+ Math.max(0, element.scrollHeight - element.clientHeight - element.scrollTop))).toBeLessThanOrEqual(1)+ expect(messagePosts).toBe(2)+ await endScrollTraceAnalysis(alice.page, "optimistic-send-away")++ await beginScrollTraceAnalysis(alice.page, "viewport-keyboard-profile")+ await markScrollTrace(alice.page, "stimulus:viewport-keyboard-profile")+ await alice.page.setViewportSize({ width: 1280, height: 560 })+ await alice.page.setViewportSize(VIEWPORT)+ await endScrollTraceAnalysis(alice.page, "viewport-keyboard-profile")+ const trace = await finishAndAttach(alice.page, testInfo)+ expect(trace.marks.filter((mark) =>+ ["optimistic-pinned", "optimistic-away"].includes(mark.name)+ && mark.dataTransitionSource === "optimistic-send")).toHaveLength(2)+ expect(trace.marks.filter((mark) => mark.dataTransitionSource === "post-ack")).toHaveLength(2)+ expect(trace.marks.filter((mark) => mark.dataTransitionSource === "ws-dedupe")).toHaveLength(2)+ expect(messageCreateCount(proxy.frames, composerChannelId, pinnedSend)).toBe(1)+ expect(messageCreateCount(proxy.frames, composerChannelId, awaySend)).toBe(1)+ })++ test.afterEach(async ({ page }) => {+ await abortScrollTrace(page)+ })+})diff --git a/src/web/src/test/e2e-ui/_fixtures/scroll-trace-browser.js b/src/web/src/test/e2e-ui/_fixtures/scroll-trace-browser.jsnew file mode 100644index 000000000..dfbdd37d9--- /dev/null+++ b/src/web/src/test/e2e-ui/_fixtures/scroll-trace-browser.js@@ -0,0 +1,551 @@+(() => {+ const GLOBAL_NAME = "__alookScrollTrace"+ const SCHEMA_VERSION = 1+ let active = null++ const round = (value) => Number.isFinite(value) ? Math.round(value * 1000) / 1000 : null+ const rect = (element) => {+ if (!element) return null+ const value = element.getBoundingClientRect()+ return {+ x: round(value.x),+ y: round(value.y),+ width: round(value.width),+ height: round(value.height),+ top: round(value.top),+ right: round(value.right),+ bottom: round(value.bottom),+ left: round(value.left),+ }+ }+ const boundedPush = (array, value, max) => {+ if (array.length < max) array.push(value)+ }+ const descriptorFor = (target, name) => {+ let owner = target+ while (owner) {+ const descriptor = Object.getOwnPropertyDescriptor(owner, name)+ if (descriptor) return { descriptor, owner }+ owner = Object.getPrototypeOf(owner)+ }+ return null+ }+ const descriptorShape = (descriptor) => descriptor ? {+ configurable: descriptor.configurable,+ enumerable: descriptor.enumerable,+ writable: descriptor.writable ?? null,+ accessor: typeof descriptor.get === "function" || typeof descriptor.set === "function",+ } : null+ const stackFingerprint = () => {+ const lines = (new Error().stack ?? "")+ .split("\n")+ .slice(3, 9)+ .map((line) => line+ .replace(/https?:\/\/[^/\s)]+/g, "<origin>")+ .replace(/([?#])[^\s)]+/g, "")+ .replace(/[A-Za-z0-9_-]{32,}/g, "<id>"))+ const sanitized = lines.join("\n")+ let hash = 2166136261+ for (let index = 0; index < sanitized.length; index += 1) {+ hash ^= sanitized.charCodeAt(index)+ hash = Math.imul(hash, 16777619)+ }+ return { fingerprint: (hash >>> 0).toString(16).padStart(8, "0"), stack: sanitized }+ }+ const patchProperty = (target, name, onCall) => {+ const effective = descriptorFor(target, name)+ const own = Object.getOwnPropertyDescriptor(target, name)+ if (+ !effective+ || !effective.descriptor.configurable+ || typeof effective.descriptor.get !== "function"+ || typeof effective.descriptor.set !== "function"+ ) {+ return {+ capability: { supported: false, descriptor: descriptorShape(effective?.descriptor) },+ restore: () => {},+ }+ }+ const original = effective.descriptor+ Object.defineProperty(target, name, {+ configurable: original.configurable,+ enumerable: original.enumerable,+ get() {+ return Reflect.apply(original.get, this, [])+ },+ set(value) {+ onCall(name, [value])+ return Reflect.apply(original.set, this, [value])+ },+ })+ return {+ capability: { supported: true, descriptor: descriptorShape(original) },+ restore: () => {+ if (own) Object.defineProperty(target, name, own)+ else delete target[name]+ },+ }+ }+ const patchMethod = (target, name, onCall) => {+ const effective = descriptorFor(target, name)+ const own = Object.getOwnPropertyDescriptor(target, name)+ if (+ !effective+ || !effective.descriptor.configurable+ || typeof effective.descriptor.value !== "function"+ ) {+ return {+ capability: { supported: false, descriptor: descriptorShape(effective?.descriptor) },+ restore: () => {},+ }+ }+ const original = effective.descriptor+ const originalMethod = original.value+ Object.defineProperty(target, name, {+ configurable: original.configurable,+ enumerable: original.enumerable,+ writable: original.writable,+ value: function (...args) {+ onCall(name, args)+ return Reflect.apply(originalMethod, this, args)+ },+ })+ return {+ capability: { supported: true, descriptor: descriptorShape(original) },+ restore: () => {+ if (own) Object.defineProperty(target, name, own)+ else delete target[name]+ },+ }+ }+ const waitForElement = (selector, timeoutMs) => new Promise((resolve, reject) => {+ const existing = document.querySelector(selector)+ if (existing) {+ resolve(existing)+ return+ }+ const timeout = window.setTimeout(() => {+ observer.disconnect()+ reject(new Error(`scroll trace target not found: ${selector}`))+ }, timeoutMs)+ const observer = new MutationObserver(() => {+ const element = document.querySelector(selector)+ if (!element) return+ window.clearTimeout(timeout)+ observer.disconnect()+ resolve(element)+ })+ observer.observe(document.documentElement, { childList: true, subtree: true })+ })+ const pillState = () => {+ const element = document.querySelector('[data-testid="community-scroll-to-present"]')+ if (!element) return { mode: null, count: 0, label: null }+ const label = element.getAttribute("aria-label") ?? ""+ const count = Number(label.match(/(\d+)/)?.[1] ?? 0)+ return {+ mode: label.startsWith("Jump to present") ? "jump" : "scroll",+ count,+ label,+ }+ }+ const loaderState = (content) => {+ const candidates = Array.from(content?.querySelectorAll(".h-8") ?? [])+ const top = candidates.find((element) => {+ const text = element.textContent ?? ""+ return text === "" || text.includes("Loading older messages")+ }) ?? null+ const bottom = candidates.find((element) =>+ (element.textContent ?? "").includes("Loading newer messages")) ?? null+ return {+ top: { mounted: !!top, loading: !!top?.textContent?.includes("Loading"), rect: rect(top) },+ bottom: { mounted: !!bottom, loading: !!bottom?.textContent?.includes("Loading"), rect: rect(bottom) },+ }+ }+ const rowSnapshot = (scroller, estimates) => {+ const rootRect = scroller.getBoundingClientRect()+ const wrappers = Array.from(scroller.querySelectorAll("[data-index]"))+ const rows = wrappers.map((wrapper) => {+ const index = Number(wrapper.getAttribute("data-index"))+ const message = wrapper.querySelector("[data-msg-id]")+ const id = message?.getAttribute("data-msg-id")+ ?? (wrapper.querySelector("[data-new-divider]") ? "new-divider" : `structural:${index}`)+ const value = wrapper.getBoundingClientRect()+ return {+ index,+ id,+ top: round(value.top),+ bottom: round(value.bottom),+ height: round(value.height),+ estimatedHeight: id in estimates ? estimates[id] : null,+ visible: value.bottom > rootRect.top && value.top < rootRect.bottom,+ }+ }).sort((left, right) => left.index - right.index)+ const visible = rows.filter((row) => row.visible)+ return {+ rows,+ domIds: rows.map((row) => row.id),+ renderedRange: rows.length ? [rows[0].index, rows.at(-1).index] : null,+ visibleRange: visible.length ? [visible[0].index, visible.at(-1).index] : null,+ firstVisibleId: visible[0]?.id ?? null,+ firstVisibleOffset: visible.length ? round(visible[0].top - rootRect.top) : null,+ lastVisibleId: visible.at(-1)?.id ?? null,+ }+ }+ const selfTest = () => {+ const receivers = []+ const proto = {}+ let stored = 2+ Object.defineProperty(proto, "value", {+ configurable: true,+ enumerable: false,+ get() {+ receivers.push(this)+ return stored+ },+ set(value) {+ receivers.push(this)+ if (value < 0) throw new RangeError("negative")+ stored = value+ },+ })+ Object.defineProperty(proto, "call", {+ configurable: true,+ enumerable: true,+ writable: false,+ value(delta) {+ if (delta < 0) throw new RangeError("negative method")+ return this.base + delta+ },+ })+ const target = Object.create(proto)+ target.base = 5+ const calls = []+ const propertyPatch = patchProperty(target, "value", (name, args) => calls.push([name, args]))+ const methodPatch = patchMethod(target, "call", (name, args) => calls.push([name, args]))+ target.value = 7+ const getterValue = target.value+ const methodValue = target.call(3)+ let setterError = null+ let methodError = null+ try { target.value = -1 } catch (error) { setterError = error.name }+ try { target.call(-1) } catch (error) { methodError = error.name }+ propertyPatch.restore()+ methodPatch.restore()+ const unsupported = {}+ Object.defineProperty(unsupported, "value", {+ configurable: false,+ get: () => 1,+ set: () => {},+ })+ const unsupportedPatch = patchProperty(unsupported, "value", () => {})+ return {+ getterValue,+ methodValue,+ setterError,+ methodError,+ receiverPreserved: receivers.every((receiver) => receiver === target),+ calls: calls.map(([name, args]) => [name, [...args]]),+ propertyDescriptor: propertyPatch.capability.descriptor,+ methodDescriptor: methodPatch.capability.descriptor,+ restored: !Object.hasOwn(target, "value") && !Object.hasOwn(target, "call"),+ unsupportedUntouched: !unsupportedPatch.capability.supported && unsupported.value === 1,+ }+ }++ const start = async (options) => {+ if (active) throw new Error("scroll trace already active")+ const selector = `[data-testid="${options.scrollerTestId}"]`+ const scroller = await waitForElement(selector, options.targetTimeoutMs ?? 20_000)+ const frames = []+ const writes = []+ const measurements = []+ const marks = []+ const externalEvents = []+ const restorers = []+ const listeners = []+ const estimates = options.estimatedSizes ?? {}+ const maxFrames = options.maxFrames ?? 2400+ const maxEvents = options.maxEvents ?? 4000+ const startedAt = performance.now()+ let frameId = 0+ let frame = 0+ let finalStimulusAt = null+ let finalStimulusFrame = null+ let stableFrames = 0+ let previousSignature = null+ let status = "recording"+ let programmaticScrollInProgress = false+ let programmaticTimer = 0+ let measurementRevision = 0+ let writerRevision = 0+ let currentMark = "start"+ let resolveFinished+ const finished = new Promise((resolve) => { resolveFinished = resolve })+ const addListener = (target, name, handler, optionsValue) => {+ target.addEventListener(name, handler, optionsValue)+ listeners.push(() => target.removeEventListener(name, handler, optionsValue))+ }+ const recordExternal = (type, detail = null) => boundedPush(externalEvents, {+ timestamp: round(performance.now()),+ type,+ detail,+ }, maxEvents)+ const recordWriter = (method, args) => {+ const stack = stackFingerprint()+ writerRevision += 1+ if (method === "scrollTo" || method === "scrollBy") {+ const first = args[0]+ const behavior = typeof first === "object" && first ? first.behavior : undefined+ if (behavior === "smooth") {+ programmaticScrollInProgress = true+ window.clearTimeout(programmaticTimer)+ programmaticTimer = window.setTimeout(() => {+ programmaticScrollInProgress = false+ }, 800)+ }+ }+ boundedPush(writes, {+ timestamp: round(performance.now()),+ frame,+ method,+ args: args.map((value) => typeof value === "number" ? round(value) : value),+ mark: currentMark,+ fingerprint: stack.fingerprint,+ stack: stack.stack,+ }, maxEvents)+ }+ const capabilities = {}+ for (const name of ["scrollTop"]) {+ const patch = patchProperty(scroller, name, recordWriter)+ capabilities[name] = patch.capability+ restorers.push(patch.restore)+ }+ for (const name of ["scrollTo", "scrollBy"]) {+ const patch = patchMethod(scroller, name, recordWriter)+ capabilities[name] = patch.capability+ restorers.push(patch.restore)+ }+ const content = scroller.querySelector("[data-message-list-content]")+ const composer = document.querySelector('[data-testid="community-composer-shell"]')+ const observedRows = new Set()+ const resizeObserver = new ResizeObserver((entries) => {+ measurementRevision += 1+ for (const entry of entries) {+ const wrapper = entry.target.closest?.("[data-index]") ?? entry.target+ const message = wrapper.querySelector?.("[data-msg-id]")+ const rawIndex = Number(wrapper.getAttribute?.("data-index"))+ boundedPush(measurements, {+ timestamp: round(performance.now()),+ frame,+ id: message?.getAttribute("data-msg-id") ?? null,+ index: Number.isFinite(rawIndex) ? rawIndex : null,+ height: round(entry.target.getBoundingClientRect().height),+ }, maxEvents)+ }+ })+ const observeRows = () => {+ for (const row of scroller.querySelectorAll("[data-index]")) {+ if (observedRows.has(row)) continue+ observedRows.add(row)+ resizeObserver.observe(row)+ }+ }+ resizeObserver.observe(scroller)+ if (content) resizeObserver.observe(content)+ if (composer) resizeObserver.observe(composer)+ observeRows()+ const mutationObserver = new MutationObserver(observeRows)+ mutationObserver.observe(scroller, { childList: true, subtree: true })+ addListener(scroller, "scroll", () => recordExternal("scroll", round(scroller.scrollTop)), { passive: true })+ addListener(scroller, "wheel", (event) => recordExternal("wheel", { x: round(event.deltaX), y: round(event.deltaY) }), { passive: true })+ addListener(scroller, "touchstart", () => recordExternal("touchstart"), { passive: true })+ addListener(scroller, "touchmove", () => recordExternal("touchmove"), { passive: true })+ addListener(scroller, "scrollend", () => {+ programmaticScrollInProgress = false+ recordExternal("scrollend")+ }, { passive: true })+ const safeControlKeys = new Set([+ "Enter",+ "Backspace",+ "Delete",+ "Tab",+ "Escape",+ "ArrowUp",+ "ArrowDown",+ "ArrowLeft",+ "ArrowRight",+ "Home",+ "End",+ "PageUp",+ "PageDown",+ "Shift",+ "Control",+ "Alt",+ "Meta",+ "CapsLock",+ ])+ addListener(window, "keydown", (event) => recordExternal(+ "keydown",+ event.key.length === 1 ? "printable" : safeControlKeys.has(event.key) ? event.key : "control",+ ), { passive: true })+ addListener(window, "resize", () => recordExternal("resize", { width: innerWidth, height: innerHeight }), { passive: true })++ const sample = () => {+ frame += 1+ const currentContent = scroller.querySelector("[data-message-list-content]")+ const currentComposer = document.querySelector('[data-testid="community-composer-shell"]')+ const currentAccessoryRail = document.querySelector('[data-testid="community-composer-accessory-rail"]')+ const rows = rowSnapshot(scroller, estimates)+ const rootRect = scroller.getBoundingClientRect()+ const tail = rows.rows.at(-1)+ const loaders = loaderState(currentContent)+ const pill = pillState()+ const max = Math.max(0, scroller.scrollHeight - scroller.clientHeight)+ const sampleValue = {+ frame,+ timestamp: round(performance.now()),+ scrollTop: round(scroller.scrollTop),+ scrollHeight: round(scroller.scrollHeight),+ clientHeight: round(scroller.clientHeight),+ browserMax: round(max),+ distanceToEnd: round(max - scroller.scrollTop),+ programmaticScrollInProgress,+ scrollerRect: rect(scroller),+ contentRect: rect(currentContent),+ composerRect: rect(currentComposer),+ accessoryRailRect: rect(currentAccessoryRail),+ tailGap: tail ? round(rootRect.bottom - tail.bottom) : null,+ newDividerRect: rect(scroller.querySelector("[data-new-divider]")),+ loaders,+ pill,+ renderedRange: rows.renderedRange,+ visibleRange: rows.visibleRange,+ firstVisibleId: rows.firstVisibleId,+ firstVisibleOffset: rows.firstVisibleOffset,+ lastVisibleId: rows.lastVisibleId,+ domIds: rows.domIds,+ rows: rows.rows,+ mark: currentMark,+ writerRevision,+ measurementRevision,+ }+ boundedPush(frames, sampleValue, maxFrames)+ if (finalStimulusAt !== null) {+ const signature = JSON.stringify([+ sampleValue.scrollTop,+ sampleValue.scrollHeight,+ sampleValue.clientHeight,+ sampleValue.firstVisibleId,+ sampleValue.firstVisibleOffset,+ sampleValue.tailGap,+ sampleValue.domIds,+ writerRevision,+ measurementRevision,+ ])+ stableFrames = signature === previousSignature ? stableFrames + 1 : 0+ previousSignature = signature+ const elapsed = performance.now() - finalStimulusAt+ const elapsedFrames = frame - finalStimulusFrame+ if (stableFrames >= 3) {+ status = "stable"+ resolveFinished()+ return+ }+ if (elapsed >= (options.settlementTimeoutMs ?? 2000) || elapsedFrames >= (options.settlementFrameCap ?? 120)) {+ status = "settlementTimedOut"+ resolveFinished()+ return+ }+ }+ if (frames.length >= maxFrames) {+ status = "settlementTimedOut"+ resolveFinished()+ return+ }+ frameId = requestAnimationFrame(sample)+ }+ frameId = requestAnimationFrame(sample)++ const mark = (name, detail = {}) => {+ currentMark = name+ const value = {+ timestamp: round(performance.now()),+ frame,+ name,+ dataTransitionSource: detail.dataTransitionSource ?? null,+ detail: detail.detail ?? null,+ preEventDistanceToEnd: round(Math.max(0, scroller.scrollHeight - scroller.clientHeight) - scroller.scrollTop),+ programmaticScrollInProgress,+ }+ boundedPush(marks, value, maxEvents)+ if (name === "final-stimulus") {+ finalStimulusAt = performance.now()+ finalStimulusFrame = frame+ stableFrames = 0+ previousSignature = null+ }+ return value+ }+ const cleanup = () => {+ cancelAnimationFrame(frameId)+ clearTimeout(programmaticTimer)+ mutationObserver.disconnect()+ resizeObserver.disconnect()+ for (const remove of listeners.splice(0)) remove()+ for (const restore of restorers.reverse()) restore()+ }+ active = {+ capabilities,+ mark,+ finished,+ finish: async () => {+ await finished+ const result = {+ schemaVersion: SCHEMA_VERSION,+ scenario: options.scenario,+ commandDirection: options.commandDirection ?? null,+ identity: options.identity,+ startedAt: round(startedAt),+ endedAt: round(performance.now()),+ status,+ capabilities,+ marks,+ frames,+ writes,+ measurements,+ externalEvents,+ dropped: {+ frames: Math.max(0, frame - frames.length),+ writes: Math.max(0, writerRevision - writes.length),+ },+ }+ cleanup()+ active = null+ delete globalThis[GLOBAL_NAME]+ return result+ },+ abort: () => {+ cleanup()+ active = null+ delete globalThis[GLOBAL_NAME]+ },+ }+ mark("start")+ return capabilities+ }++ globalThis[GLOBAL_NAME] = {+ schemaVersion: SCHEMA_VERSION,+ selfTest,+ start,+ mark: (name, detail) => {+ if (!active) throw new Error("scroll trace is not active")+ return active.mark(name, detail)+ },+ finish: () => {+ if (!active) throw new Error("scroll trace is not active")+ return active.finish()+ },+ abort: () => active?.abort(),+ }+})()diff --git a/src/web/src/test/e2e-ui/_fixtures/scroll-trace.ts b/src/web/src/test/e2e-ui/_fixtures/scroll-trace.tsnew file mode 100644index 000000000..04c69cc7a--- /dev/null+++ b/src/web/src/test/e2e-ui/_fixtures/scroll-trace.ts@@ -0,0 +1,705 @@+import { createHash } from "node:crypto"+import { execFileSync } from "node:child_process"+import { existsSync, readFileSync } from "node:fs"+import { resolve } from "node:path"+import type { Page, TestInfo } from "@playwright/test"++export const SCROLL_TRACE_SCHEMA_VERSION = 1+export const SCROLL_TRACE_PROFILE_VERSION = "message-scroll-v1"+const repoRoot = existsSync(resolve(process.cwd(), "pnpm-lock.yaml"))+ ? process.cwd()+ : resolve(process.cwd(), "../..")+export const SCROLL_TRACE_PROBE_PATH = resolve(+ repoRoot,+ "src/web/src/test/e2e-ui/_fixtures/scroll-trace-browser.js",+)++export type ScrollTraceStatus = "stable" | "settlementTimedOut"+export type ScrollTraceDataSource =+ | "initial-cold"+ | "initial-cache"+ | "older-page"+ | "newer-page"+ | "anchor-swap"+ | "overlay-ws"+ | "optimistic-send"+ | "post-ack"+ | "ws-dedupe"++export interface ScrollTraceIdentity {+ sourceSha: string+ lockHash: string+ servedBuildId: string+ probeHash: string+ profileVersion: string+ runtime: string+ account: string+ channel: string+ viewport: { width: number; height: number; dpr: number }+}++export interface ScrollTraceRect {+ x: number+ y: number+ width: number+ height: number+ top: number+ right: number+ bottom: number+ left: number+}++export interface ScrollTraceRow {+ index: number+ id: string+ top: number+ bottom: number+ height: number+ estimatedHeight: number | null+ visible: boolean+}++export interface ScrollTraceFrame {+ frame: number+ timestamp: number+ scrollTop: number+ scrollHeight: number+ clientHeight: number+ browserMax: number+ distanceToEnd: number+ programmaticScrollInProgress: boolean+ scrollerRect: ScrollTraceRect | null+ contentRect: ScrollTraceRect | null+ composerRect: ScrollTraceRect | null+ accessoryRailRect: ScrollTraceRect | null+ tailGap: number | null+ newDividerRect: ScrollTraceRect | null+ loaders: {+ top: { mounted: boolean; loading: boolean; rect: ScrollTraceRect | null }+ bottom: { mounted: boolean; loading: boolean; rect: ScrollTraceRect | null }+ }+ pill: { mode: "jump" | "scroll" | null; count: number; label: string | null }+ renderedRange: [number, number] | null+ visibleRange: [number, number] | null+ firstVisibleId: string | null+ firstVisibleOffset: number | null+ lastVisibleId: string | null+ domIds: string[]+ rows: ScrollTraceRow[]+ mark: string+ writerRevision: number+ measurementRevision: number+}++export interface ScrollTraceWrite {+ timestamp: number+ frame: number+ method: string+ args: unknown[]+ mark: string+ fingerprint: string+ stack: string+}++export interface ScrollTraceMark {+ timestamp: number+ frame: number+ name: string+ dataTransitionSource: ScrollTraceDataSource | null+ detail: unknown+ preEventDistanceToEnd: number+ programmaticScrollInProgress: boolean+}++export interface ScrollTraceResult {+ schemaVersion: number+ scenario: string+ commandDirection: "forward" | "backward" | null+ identity: ScrollTraceIdentity+ startedAt: number+ endedAt: number+ status: ScrollTraceStatus+ capabilities: Record<string, { supported: boolean; descriptor: unknown }>+ marks: ScrollTraceMark[]+ frames: ScrollTraceFrame[]+ writes: ScrollTraceWrite[]+ measurements: Array<{+ timestamp: number+ frame: number+ id: string | null+ index: number | null+ height: number+ }>+ externalEvents: Array<{ timestamp: number; type: string; detail: unknown }>+ dropped: { frames: number; writes: number }+}++export interface ScrollTraceMetrics {+ finalProgress: number+ reversalCount: number+ maxReversalPx: number+ zeroProgressFrames: number+ frameDelta: { p50: number; p95: number; max: number }+ anchorDriftPx: number | null+ tailGapDriftPx: number | null+ writerCount: number+ contentionEpochs: Array<{ frame: number; owners: string[] }>+ unknownWriterCount: number+ measurementCount: number+ repeatedMeasurementRows: Array<{ id: string; count: number }>+ estimateErrorPx: { p50: number; p95: number; max: number } | null+}++export interface ScrollTraceAnalysisSegment extends ScrollTraceMetrics {+ name: string+ commandDirection: "forward" | "backward" | null+ startFrame: number+ endFrame: number+ frameCount: number+}++export interface ScrollTraceSummary extends ScrollTraceMetrics {+ scenario: string+ status: ScrollTraceStatus+ frameCount: number+ analysisFrameCount: number+ settlementFrames: number+ analysisSegments: ScrollTraceAnalysisSegment[]+}++type BrowserTraceApi = {+ schemaVersion: number+ selfTest: () => unknown+ start: (options: unknown) => Promise<unknown>+ mark: (name: string, detail?: unknown) => unknown+ finish: () => Promise<ScrollTraceResult>+ abort: () => void+}++export function readScrollTraceProbe(): { source: string; hash: string } {+ const source = readFileSync(SCROLL_TRACE_PROBE_PATH, "utf8")+ return { source, hash: createHash("sha256").update(source).digest("hex") }+}++export function createScrollTraceIdentity(input: {+ account: string+ channel: string+ runtime?: string+ servedBuildId?: string+ viewport: { width: number; height: number; dpr?: number }+}): ScrollTraceIdentity {+ const sourceSha = process.env.GITHUB_SHA+ ?? execFileSync("git", ["rev-parse", "HEAD"], { cwd: repoRoot, encoding: "utf8" }).trim()+ const lockHash = createHash("sha256")+ .update(readFileSync(resolve(repoRoot, "pnpm-lock.yaml")))+ .digest("hex")+ const probeHash = readScrollTraceProbe().hash+ return {+ sourceSha,+ lockHash,+ servedBuildId: input.servedBuildId+ ?? process.env.ALOOK_TRACE_BUILD_ID+ ?? `${sourceSha}:${lockHash.slice(0, 16)}`,+ probeHash,+ profileVersion: SCROLL_TRACE_PROFILE_VERSION,+ runtime: input.runtime ?? "chromium",+ account: input.account,+ channel: input.channel,+ viewport: {+ ...input.viewport,+ dpr: input.viewport.dpr ?? 1,+ },+ }+}++export async function installScrollTrace(page: Page): Promise<{ probeHash: string }> {+ const probe = readScrollTraceProbe()+ await page.addInitScript({ content: probe.source })+ return { probeHash: probe.hash }+}++export async function installScrollTraceInCurrentDocument(page: Page): Promise<{ probeHash: string }> {+ const probe = readScrollTraceProbe()+ await page.addScriptTag({ content: probe.source })+ return { probeHash: probe.hash }+}++export async function scrollTraceSelfTest(page: Page): Promise<unknown> {+ return page.evaluate(() => {+ const api = (globalThis as typeof globalThis & { __alookScrollTrace?: BrowserTraceApi })+ .__alookScrollTrace+ if (!api) throw new Error("scroll trace probe is not installed")+ return api.selfTest()+ })+}++export async function startScrollTrace(page: Page, input: {+ scenario: string+ identity: ScrollTraceIdentity+ commandDirection?: "forward" | "backward"+ estimatedSizes?: Record<string, number>+ maxFrames?: number+}): Promise<unknown> {+ return page.evaluate((options) => {+ const api = (globalThis as typeof globalThis & { __alookScrollTrace?: BrowserTraceApi })+ .__alookScrollTrace+ if (!api) throw new Error("scroll trace probe is not installed")+ return api.start({+ scrollerTestId: "community-message-scroller",+ settlementTimeoutMs: 2000,+ settlementFrameCap: 120,+ maxFrames: 2400,+ ...options,+ })+ }, input)+}++export async function markScrollTrace(+ page: Page,+ name: string,+ input?: { dataTransitionSource?: ScrollTraceDataSource; detail?: unknown },+): Promise<ScrollTraceMark> {+ return page.evaluate(+ ({ mark, detail }) => {+ const api = (globalThis as typeof globalThis & { __alookScrollTrace?: BrowserTraceApi })+ .__alookScrollTrace+ if (!api) throw new Error("scroll trace probe is not installed")+ return api.mark(mark, detail) as ScrollTraceMark+ },+ { mark: name, detail: input },+ )+}++export async function beginScrollTraceAnalysis(+ page: Page,+ name: string,+ input?: {+ dataTransitionSource?: ScrollTraceDataSource+ detail?: unknown+ commandDirection?: "forward" | "backward"+ },+): Promise<ScrollTraceMark> {+ return markScrollTrace(page, `analysis-start:${name}`, {+ dataTransitionSource: input?.dataTransitionSource,+ detail: {+ commandDirection: input?.commandDirection ?? null,+ value: input?.detail ?? null,+ },+ })+}++export async function endScrollTraceAnalysis(page: Page, name: string): Promise<ScrollTraceMark> {+ await page.evaluate(() => new Promise<void>((resolveValue) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolveValue()))+ }))+ return markScrollTrace(page, `analysis-end:${name}`)+}++export async function finishScrollTrace(page: Page): Promise<ScrollTraceResult> {+ return page.evaluate(() => {+ const api = (globalThis as typeof globalThis & { __alookScrollTrace?: BrowserTraceApi })+ .__alookScrollTrace+ if (!api) throw new Error("scroll trace probe is not installed")+ return api.finish()+ })+}++export async function abortScrollTrace(page: Page): Promise<void> {+ await page.evaluate(() => {+ const api = (globalThis as typeof globalThis & { __alookScrollTrace?: BrowserTraceApi })+ .__alookScrollTrace+ api?.abort()+ }).catch(() => {})+}++export async function attachScrollTrace(+ testInfo: TestInfo,+ result: ScrollTraceResult,+): Promise<ScrollTraceSummary> {+ const validation = validateScrollTrace(result)+ if (validation.length > 0) throw new Error(`invalid scroll trace: ${validation.join("; ")}`)+ const summary = summarizeScrollTrace(result)+ await testInfo.attach(`${result.scenario}.scroll-trace.json`, {+ body: Buffer.from(JSON.stringify(result)),+ contentType: "application/json",+ })+ await testInfo.attach(`${result.scenario}.scroll-summary.json`, {+ body: Buffer.from(JSON.stringify(summary)),+ contentType: "application/json",+ })+ return summary+}++export function validateScrollTrace(result: ScrollTraceResult): string[] {+ const errors: string[] = []+ if (result.schemaVersion !== SCROLL_TRACE_SCHEMA_VERSION) errors.push("schema version")+ if (!result.scenario) errors.push("scenario")+ if (!result.identity?.sourceSha || !result.identity.lockHash || !result.identity.probeHash) {+ errors.push("identity")+ }+ if (result.status !== "stable" && result.status !== "settlementTimedOut") errors.push("status")+ if (!result.marks.some((mark) => mark.name === "final-stimulus")) errors.push("final-stimulus mark")+ const analysisStarts = result.marks.filter((mark) => mark.name.startsWith("analysis-start:"))+ const analysisEnds = result.marks.filter((mark) => mark.name.startsWith("analysis-end:"))+ const analysisWindows = collectAnalysisWindows(result)+ if (+ analysisStarts.length === 0+ || analysisStarts.length !== analysisEnds.length+ || analysisWindows.length !== analysisStarts.length+ || analysisWindows.some((window) => window.frames.length < 2)+ ) errors.push("analysis window")+ let timestamp = -Infinity+ for (const frame of result.frames) {+ if (frame.timestamp < timestamp) errors.push("non-monotonic timestamp")+ timestamp = frame.timestamp+ for (const value of [+ frame.scrollTop,+ frame.scrollHeight,+ frame.clientHeight,+ frame.browserMax,+ frame.distanceToEnd,+ ]) {+ if (!Number.isFinite(value)) errors.push("non-finite geometry")+ }+ }+ const safeKeyDetails = new Set([+ "printable",+ "Enter",+ "Backspace",+ "Delete",+ "Tab",+ "Escape",+ "ArrowUp",+ "ArrowDown",+ "ArrowLeft",+ "ArrowRight",+ "Home",+ "End",+ "PageUp",+ "PageDown",+ "Shift",+ "Control",+ "Alt",+ "Meta",+ "CapsLock",+ "control",+ ])+ if (result.externalEvents.some((event) =>+ event.type === "keydown"+ && (typeof event.detail !== "string" || !safeKeyDetails.has(event.detail)))) {+ errors.push("unsafe key detail")+ }+ const serialized = JSON.stringify(result)+ if (/cookie|authorization|set-cookie|better-auth/i.test(serialized)) errors.push("sensitive field")+ return [...new Set(errors)]+}++export function inferWriterOwner(write: ScrollTraceWrite): string {+ const stack = write.stack.toLowerCase()+ if (stack.includes("virtual-core") || stack.includes("tanstack")) return "tanstack-virtual"+ if (stack.includes("use-scroll-anchor")) return "scroll-anchor"+ if (stack.includes("message-list-controller")) return "selection-clearance"+ if (stack.includes("scroll-trace")) return "test-stimulus"+ return `unknown:${write.fingerprint}`+}++export function coalesceWriterCalls(writes: ScrollTraceWrite[]): Array<{+ owner: string+ firstFrame: number+ lastFrame: number+ calls: ScrollTraceWrite[]+}> {+ const epochs: Array<{+ owner: string+ firstFrame: number+ lastFrame: number+ calls: ScrollTraceWrite[]+ }> = []+ for (const write of writes) {+ const owner = inferWriterOwner(write)+ const previous = epochs.at(-1)+ if (previous && previous.owner === owner && write.frame - previous.lastFrame <= 1) {+ previous.lastFrame = write.frame+ previous.calls.push(write)+ } else {+ epochs.push({ owner, firstFrame: write.frame, lastFrame: write.frame, calls: [write] })+ }+ }+ return epochs+}++function percentile(values: number[], value: number): number {+ if (values.length === 0) return 0+ const sorted = [...values].sort((left, right) => left - right)+ return sorted[Math.min(sorted.length - 1, Math.ceil(sorted.length * value) - 1)]!+}++type AnalysisWindow = {+ name: string+ commandDirection: "forward" | "backward" | null+ startFrame: number+ endFrame: number+ frames: ScrollTraceFrame[]+ writes: ScrollTraceWrite[]+ measurements: ScrollTraceResult["measurements"]+}++function collectAnalysisWindows(result: ScrollTraceResult): AnalysisWindow[] {+ const windows: AnalysisWindow[] = []+ const starts = new Map<string, ScrollTraceMark>()+ for (const mark of result.marks) {+ if (mark.name.startsWith("analysis-start:")) {+ const name = mark.name.slice("analysis-start:".length)+ if (name && !starts.has(name)) starts.set(name, mark)+ continue+ }+ if (!mark.name.startsWith("analysis-end:")) continue+ const name = mark.name.slice("analysis-end:".length)+ const start = starts.get(name)+ if (!name || !start || mark.frame < start.frame) continue+ windows.push({+ name,+ commandDirection: typeof start.detail === "object"+ && start.detail !== null+ && "commandDirection" in start.detail+ && (start.detail.commandDirection === "forward" || start.detail.commandDirection === "backward")+ ? start.detail.commandDirection+ : null,+ startFrame: start.frame,+ endFrame: mark.frame,+ frames: result.frames.filter((frame) => frame.frame >= start.frame && frame.frame <= mark.frame),+ writes: result.writes.filter((write) => write.frame >= start.frame && write.frame <= mark.frame),+ measurements: result.measurements.filter((measurement) =>+ measurement.frame >= start.frame && measurement.frame <= mark.frame),+ })+ starts.delete(name)+ }+ return windows+}++function summarizeWindow(window: AnalysisWindow): ScrollTraceAnalysisSegment & { deltas: number[] } {+ const deltas = window.frames.slice(1).map((frame, index) =>+ frame.scrollTop - window.frames[index]!.scrollTop)+ const absoluteDeltas = deltas.map(Math.abs)+ const direction = window.commandDirection === "backward"+ ? -1+ : window.commandDirection === "forward"+ ? 1+ : null+ const reversals = direction === null ? [] : deltas.filter((delta) => delta * direction < -4)+ const epochs = coalesceWriterCalls(window.writes)+ const ownersByFrame = new Map<number, Set<string>>()+ for (const epoch of epochs) {+ for (let frame = epoch.firstFrame; frame <= epoch.lastFrame; frame += 1) {+ const owners = ownersByFrame.get(frame) ?? new Set<string>()+ owners.add(epoch.owner)+ ownersByFrame.set(frame, owners)+ }+ }+ const measurementCounts = new Map<string, number>()+ for (const measurement of window.measurements) {+ if (!measurement.id) continue+ measurementCounts.set(measurement.id, (measurementCounts.get(measurement.id) ?? 0) + 1)+ }+ const finalRows = window.frames.at(-1)?.rows ?? []+ const estimateErrors = finalRows.flatMap((row) => row.estimatedHeight === null+ ? []+ : [Math.abs(row.height - row.estimatedHeight)])+ const first = window.frames[0]+ const last = window.frames.at(-1)+ const matchingAnchor = first && last && first.firstVisibleId === last.firstVisibleId+ return {+ name: window.name,+ commandDirection: window.commandDirection,+ startFrame: window.startFrame,+ endFrame: window.endFrame,+ frameCount: window.frames.length,+ finalProgress: first && last ? last.scrollTop - first.scrollTop : 0,+ reversalCount: reversals.length,+ maxReversalPx: reversals.length ? Math.max(...reversals.map(Math.abs)) : 0,+ zeroProgressFrames: deltas.filter((delta) => Math.abs(delta) < 0.01).length,+ frameDelta: {+ p50: percentile(absoluteDeltas, 0.5),+ p95: percentile(absoluteDeltas, 0.95),+ max: absoluteDeltas.length ? Math.max(...absoluteDeltas) : 0,+ },+ anchorDriftPx: matchingAnchor && first.firstVisibleOffset !== null && last.firstVisibleOffset !== null+ ? last.firstVisibleOffset - first.firstVisibleOffset+ : null,+ tailGapDriftPx: first?.tailGap !== null && first?.tailGap !== undefined && last?.tailGap !== null && last?.tailGap !== undefined+ ? last.tailGap - first.tailGap+ : null,+ writerCount: window.writes.length,+ contentionEpochs: [...ownersByFrame.entries()]+ .filter(([, owners]) => owners.size > 1)+ .map(([frame, owners]) => ({ frame, owners: [...owners].sort() })),+ unknownWriterCount: epochs.filter((epoch) => epoch.owner.startsWith("unknown:"))+ .reduce((count, epoch) => count + epoch.calls.length, 0),+ measurementCount: window.measurements.length,+ repeatedMeasurementRows: [...measurementCounts.entries()]+ .filter(([, count]) => count > 1)+ .map(([id, count]) => ({ id, count }))+ .sort((left, right) => right.count - left.count || left.id.localeCompare(right.id)),+ estimateErrorPx: estimateErrors.length ? {+ p50: percentile(estimateErrors, 0.5),+ p95: percentile(estimateErrors, 0.95),+ max: Math.max(...estimateErrors),+ } : null,+ deltas,+ }+}++function largestMagnitude(values: Array<number | null>): number | null {+ const finite = values.filter((value): value is number => value !== null)+ return finite.reduce<number | null>((largest, value) =>+ largest === null || Math.abs(value) > Math.abs(largest) ? value : largest, null)+}++export function summarizeScrollTrace(result: ScrollTraceResult): ScrollTraceSummary {+ const finalMark = result.marks.find((mark) => mark.name === "final-stimulus")+ const finalFrames = finalMark+ ? result.frames.filter((frame) => frame.frame >= finalMark.frame)+ : result.frames+ const analysisWindows = collectAnalysisWindows(result)+ const segmentDetails = analysisWindows.map(summarizeWindow)+ const deltas = segmentDetails.flatMap((segment) => segment.deltas)+ const absoluteDeltas = deltas.map(Math.abs)+ const analysisSegments = segmentDetails.map(({ deltas: _deltas, ...segment }) => segment)+ const estimateErrors = analysisSegments.flatMap((segment) => segment.estimateErrorPx+ ? [segment.estimateErrorPx]+ : [])+ const measurementCounts = new Map<string, number>()+ for (const measurement of analysisWindows.flatMap((window) => window.measurements)) {+ if (!measurement.id) continue+ measurementCounts.set(measurement.id, (measurementCounts.get(measurement.id) ?? 0) + 1)+ }+ return {+ scenario: result.scenario,+ status: result.status,+ frameCount: result.frames.length,+ analysisFrameCount: analysisSegments.reduce((count, segment) => count + segment.frameCount, 0),+ settlementFrames: finalFrames.length,+ analysisSegments,+ finalProgress: analysisSegments.reduce((total, segment) => total + segment.finalProgress, 0),+ reversalCount: analysisSegments.reduce((total, segment) => total + segment.reversalCount, 0),+ maxReversalPx: Math.max(0, ...analysisSegments.map((segment) => segment.maxReversalPx)),+ zeroProgressFrames: deltas.filter((delta) => Math.abs(delta) < 0.01).length,+ frameDelta: {+ p50: percentile(absoluteDeltas, 0.5),+ p95: percentile(absoluteDeltas, 0.95),+ max: absoluteDeltas.length ? Math.max(...absoluteDeltas) : 0,+ },+ anchorDriftPx: largestMagnitude(analysisSegments.map((segment) => segment.anchorDriftPx)),+ tailGapDriftPx: largestMagnitude(analysisSegments.map((segment) => segment.tailGapDriftPx)),+ writerCount: analysisSegments.reduce((total, segment) => total + segment.writerCount, 0),+ contentionEpochs: analysisSegments.flatMap((segment) => segment.contentionEpochs),+ unknownWriterCount: analysisSegments.reduce((total, segment) =>+ total + segment.unknownWriterCount, 0),+ measurementCount: analysisSegments.reduce((total, segment) => total + segment.measurementCount, 0),+ repeatedMeasurementRows: [...measurementCounts.entries()]+ .filter(([, count]) => count > 1)+ .map(([id, count]) => ({ id, count }))+ .sort((left, right) => right.count - left.count || left.id.localeCompare(right.id)),+ estimateErrorPx: estimateErrors.length ? {+ p50: percentile(estimateErrors.map((error) => error.p50), 0.5),+ p95: percentile(estimateErrors.map((error) => error.p95), 0.95),+ max: Math.max(...estimateErrors.map((error) => error.max)),+ } : null,+ }+}++export function nativeMargin(+ observed: number,+ unit: "css-px" | "count" | "ms" | "percentage-point",+): number {+ if (unit === "percentage-point") return Math.max(0.1, Math.abs(observed) * 0.05)+ if (unit === "count") return Math.max(1, Math.ceil(Math.abs(observed) * 0.05))+ return Math.max(1, Math.abs(observed) * 0.05)+}++export function classifyTracePair(+ web: ScrollTraceResult,+ desktop: ScrollTraceResult,+): { classification: "matched" | "platform-regression" | "unclassified"; reasons: string[] } {+ const reasons: string[] = []+ if (web.identity.runtime !== "chromium") reasons.push("runtime:web")+ if (desktop.identity.runtime !== "tauri") reasons.push("runtime:desktop")+ for (const key of [+ "sourceSha",+ "lockHash",+ "servedBuildId",+ "probeHash",+ "profileVersion",+ "account",+ "channel",+ ] as const) {+ if (web.identity[key] !== desktop.identity[key]) reasons.push(`identity:${key}`)+ }+ for (const key of ["width", "height", "dpr"] as const) {+ if (web.identity.viewport[key] !== desktop.identity.viewport[key]) reasons.push(`viewport:${key}`)+ }+ if (web.scenario !== desktop.scenario) reasons.push("scenario")+ const webAnalysisFrame = collectAnalysisWindows(web)[0]?.frames[0]+ const desktopAnalysisFrame = collectAnalysisWindows(desktop)[0]?.frames[0]+ if (!webAnalysisFrame?.scrollerRect || !desktopAnalysisFrame?.scrollerRect) {+ reasons.push("matched-evidence:scroller")+ } else {+ if (webAnalysisFrame.scrollerRect.width !== desktopAnalysisFrame.scrollerRect.width) {+ reasons.push("scroller:width")+ }+ if (webAnalysisFrame.scrollerRect.height !== desktopAnalysisFrame.scrollerRect.height) {+ reasons.push("scroller:height")+ }+ }+ const inputTypes = new Set(["wheel", "touchstart", "touchmove", "keydown", "resize"])+ const webInputs = web.externalEvents.filter((event) => inputTypes.has(event.type))+ const desktopInputs = desktop.externalEvents.filter((event) => inputTypes.has(event.type))+ if (webInputs.length === 0 || desktopInputs.length === 0) {+ reasons.push("matched-evidence:input-cadence")+ } else if (+ webInputs.length !== desktopInputs.length+ || webInputs.some((event, index) => {+ const other = desktopInputs[index]!+ if (event.type !== other.type || JSON.stringify(event.detail) !== JSON.stringify(other.detail)) return true+ if (index === 0) return false+ const webGap = event.timestamp - webInputs[index - 1]!.timestamp+ const desktopGap = other.timestamp - desktopInputs[index - 1]!.timestamp+ return Math.abs(webGap - desktopGap) > nativeMargin(webGap, "ms")+ })+ ) {+ reasons.push("input-cadence")+ }+ const writerSequence = (trace: ScrollTraceResult) => trace.writes.map((write) => ({+ owner: inferWriterOwner(write),+ method: write.method,+ mark: write.mark,+ }))+ if (web.writes.length === 0 || desktop.writes.length === 0) {+ reasons.push("matched-evidence:writer-sequence")+ } else if (JSON.stringify(writerSequence(web)) !== JSON.stringify(writerSequence(desktop))) {+ reasons.push("writer-sequence")+ }+ const measurementSequence = (trace: ScrollTraceResult) => trace.measurements.map((measurement) => ({+ id: measurement.id,+ index: measurement.index,+ height: measurement.height,+ }))+ if (web.measurements.length === 0 || desktop.measurements.length === 0) {+ reasons.push("matched-evidence:measurement-sequence")+ } else if (JSON.stringify(measurementSequence(web)) !== JSON.stringify(measurementSequence(desktop))) {+ reasons.push("measurement-sequence")+ }+ if (reasons.length > 0) return { classification: "unclassified", reasons }+ const webSummary = summarizeScrollTrace(web)+ const desktopSummary = summarizeScrollTrace(desktop)+ const reversalLimit = webSummary.reversalCount + nativeMargin(webSummary.reversalCount, "count")+ const driftBaseline = Math.abs(webSummary.anchorDriftPx ?? 0)+ const driftLimit = driftBaseline + nativeMargin(driftBaseline, "css-px")+ if (+ desktopSummary.reversalCount > reversalLimit+ || Math.abs(desktopSummary.anchorDriftPx ?? 0) > driftLimit+ ) {+ return { classification: "platform-regression", reasons: ["matched identity with larger Desktop drift"] }+ }+ return { classification: "matched", reasons: [] }+}diff --git a/src/web/src/test/fixtures/message-scroll-baseline.json b/src/web/src/test/fixtures/message-scroll-baseline.jsonnew file mode 100644index 000000000..dc8f88d03--- /dev/null+++ b/src/web/src/test/fixtures/message-scroll-baseline.json@@ -0,0 +1,203 @@+{+ "schemaVersion": 1,+ "profileVersion": "message-scroll-v1",+ "sourceIdentity": {+ "sourceSha": "6396fe02a061f960b67516a5a0446bfb82514cdf",+ "lockHash": "691443b5cbe8fffe73b061fc23209b82d1cfd5884c125b5c3aafb03fb86bbe93",+ "servedBuildId": "6396fe02a061f960b67516a5a0446bfb82514cdf:691443b5cbe8fffe",+ "probeHash": "12fe64c1db42a698207a426b540e8cea62a2e67c80f9dc245616da3095019289",+ "runtime": "chromium",+ "viewport": {+ "width": 1280,+ "height": 800,+ "dpr": 1+ }+ },+ "capture": {+ "successfulMatrixRuns": 2,+ "settlementRule": "3 unchanged RAFs after final-stimulus, bounded by 120 RAFs or 2000 ms",+ "portablePerformanceGate": false+ },+ "units": {+ "frameCount": "count",+ "analysisFrameCount": "count",+ "settlementFrames": "count",+ "finalProgress": "css-px",+ "reversalCount": "count",+ "maxReversalPx": "css-px",+ "zeroProgressFrames": "count",+ "frameDelta": "css-px",+ "anchorDriftPx": "css-px",+ "tailGapDriftPx": "css-px",+ "writerCount": "count",+ "contentionEpochCount": "count",+ "unknownWriterCount": "count",+ "measurementCount": "count",+ "repeatedMeasurementRowCount": "count",+ "maxMeasurementsPerRow": "count",+ "estimateErrorPx": "css-px"+ },+ "gatePolicy": {+ "hard": [+ "trace schema and finite geometry",+ "explicit final-stimulus and terminal status",+ "existing request, mutation, send, and dedupe contracts asserted by the spec"+ ],+ "diagnostic": [+ "settlement timeout",+ "writer ownership and contention",+ "reversal and stall counts",+ "anchor and tail-gap drift",+ "measurement churn and estimate error",+ "frame-delta p95 and max"+ ]+ },+ "observations": {+ "cold-load-and-async-row": {+ "status": "stable",+ "frameCount": 688,+ "analysisFrameCount": 684,+ "settlementFrames": 5,+ "finalProgress": 1623,+ "reversalCount": 0,+ "maxReversalPx": 0,+ "zeroProgressFrames": 671,+ "frameDelta": { "p50": 0, "p95": 0, "max": 495 },+ "anchorDriftPx": null,+ "tailGapDriftPx": null,+ "writerCount": 31,+ "contentionEpochCount": 14,+ "unknownWriterCount": 31,+ "measurementCount": 33,+ "repeatedMeasurementRowCount": 4,+ "maxMeasurementsPerRow": 14,+ "estimateErrorPx": null,+ "segments": [+ { "name": "cold-load-and-async-row", "commandDirection": null, "frameCount": 684, "finalProgress": 1623, "reversalCount": 0, "maxReversalPx": 0 }+ ]+ },+ "warm-cache-revalidation": {+ "status": "stable",+ "frameCount": 7,+ "analysisFrameCount": 3,+ "settlementFrames": 5,+ "finalProgress": 0,+ "reversalCount": 0,+ "maxReversalPx": 0,+ "zeroProgressFrames": 2,+ "frameDelta": { "p50": 0, "p95": 0, "max": 0 },+ "anchorDriftPx": 0,+ "tailGapDriftPx": 0,+ "writerCount": 0,+ "contentionEpochCount": 0,+ "unknownWriterCount": 0,+ "measurementCount": 12,+ "repeatedMeasurementRowCount": 1,+ "maxMeasurementsPerRow": 3,+ "estimateErrorPx": { "p50": 57.5, "p95": 494, "max": 494 },+ "segments": [+ { "name": "warm-cache-revalidation", "commandDirection": null, "frameCount": 3, "finalProgress": 0, "reversalCount": 0, "maxReversalPx": 0 }+ ]+ },+ "older-loading-prepend": {+ "status": "stable",+ "frameCount": 48,+ "analysisFrameCount": 42,+ "settlementFrames": 5,+ "finalProgress": -4145,+ "reversalCount": 1,+ "maxReversalPx": 77,+ "zeroProgressFrames": 39,+ "frameDelta": { "p50": 0, "p95": 0, "max": 4222 },+ "anchorDriftPx": null,+ "tailGapDriftPx": 55,+ "writerCount": 2,+ "contentionEpochCount": 0,+ "unknownWriterCount": 2,+ "measurementCount": 61,+ "repeatedMeasurementRowCount": 13,+ "maxMeasurementsPerRow": 3,+ "estimateErrorPx": { "p50": 34.422, "p95": 158.422, "max": 158.422 },+ "segments": [+ { "name": "older-loading-prepend", "commandDirection": "backward", "frameCount": 42, "finalProgress": -4145, "reversalCount": 1, "maxReversalPx": 77 }+ ]+ },+ "newer-loading-present": {+ "status": "stable",+ "frameCount": 99,+ "analysisFrameCount": 95,+ "settlementFrames": 5,+ "finalProgress": 6547,+ "reversalCount": 3,+ "maxReversalPx": 147,+ "zeroProgressFrames": 89,+ "frameDelta": { "p50": 0, "p95": 60, "max": 5834 },+ "anchorDriftPx": null,+ "tailGapDriftPx": 1537,+ "writerCount": 27,+ "contentionEpochCount": 4,+ "unknownWriterCount": 27,+ "measurementCount": 73,+ "repeatedMeasurementRowCount": 26,+ "maxMeasurementsPerRow": 4,+ "estimateErrorPx": { "p50": 33.922, "p95": 158.422, "max": 158.422 },+ "segments": [+ { "name": "newer-loading-present", "commandDirection": "forward", "frameCount": 95, "finalProgress": 6547, "reversalCount": 3, "maxReversalPx": 147 }+ ]+ },+ "remote-receive-and-upward-input": {+ "status": "stable",+ "frameCount": 597,+ "analysisFrameCount": 557,+ "settlementFrames": 5,+ "finalProgress": 7187,+ "reversalCount": 0,+ "maxReversalPx": 0,+ "zeroProgressFrames": 460,+ "frameDelta": { "p50": 0, "p95": 24, "max": 3385 },+ "anchorDriftPx": 0,+ "tailGapDriftPx": -1274.422,+ "writerCount": 19,+ "contentionEpochCount": 1,+ "unknownWriterCount": 19,+ "measurementCount": 134,+ "repeatedMeasurementRowCount": 42,+ "maxMeasurementsPerRow": 7,+ "estimateErrorPx": { "p50": 33.922, "p95": 158.422, "max": 172.422 },+ "segments": [+ { "name": "remote-pinned", "commandDirection": null, "frameCount": 79, "finalProgress": 4051, "reversalCount": 0, "maxReversalPx": 0 },+ { "name": "remote-away-101", "commandDirection": null, "frameCount": 67, "finalProgress": 0, "reversalCount": 0, "maxReversalPx": 0 },+ { "name": "remote-mid-history-burst", "commandDirection": null, "frameCount": 144, "finalProgress": 0, "reversalCount": 0, "maxReversalPx": 0 },+ { "name": "remote-during-smooth", "commandDirection": "forward", "frameCount": 68, "finalProgress": 4608, "reversalCount": 0, "maxReversalPx": 0 },+ { "name": "upward-60x24", "commandDirection": "backward", "frameCount": 199, "finalProgress": -1472, "reversalCount": 0, "maxReversalPx": 0 }+ ]+ },+ "composer-clear-send-and-viewport": {+ "status": "stable",+ "frameCount": 366,+ "analysisFrameCount": 180,+ "settlementFrames": 5,+ "finalProgress": 235,+ "reversalCount": 0,+ "maxReversalPx": 0,+ "zeroProgressFrames": 170,+ "frameDelta": { "p50": 0, "p95": 0, "max": 339 },+ "anchorDriftPx": -39,+ "tailGapDriftPx": 300,+ "writerCount": 11,+ "contentionEpochCount": 1,+ "unknownWriterCount": 11,+ "measurementCount": 12,+ "repeatedMeasurementRowCount": 1,+ "maxMeasurementsPerRow": 6,+ "estimateErrorPx": { "p50": 57.5, "p95": 494, "max": 494 },+ "segments": [+ { "name": "manual-delete-pinned", "commandDirection": null, "frameCount": 7, "finalProgress": -23, "reversalCount": 0, "maxReversalPx": 0 },+ { "name": "manual-delete-away", "commandDirection": null, "frameCount": 5, "finalProgress": -120, "reversalCount": 0, "maxReversalPx": 0 },+ { "name": "optimistic-send-pinned", "commandDirection": null, "frameCount": 55, "finalProgress": 39, "reversalCount": 0, "maxReversalPx": 0 },+ { "name": "optimistic-send-away", "commandDirection": null, "frameCount": 109, "finalProgress": 339, "reversalCount": 0, "maxReversalPx": 0 },+ { "name": "viewport-keyboard-profile", "commandDirection": null, "frameCount": 4, "finalProgress": 0, "reversalCount": 0, "maxReversalPx": 0 }+ ]+ }+ }+}diff --git a/src/web/src/test/scroll-trace.test.ts b/src/web/src/test/scroll-trace.test.tsnew file mode 100644index 000000000..cb649f8ac--- /dev/null+++ b/src/web/src/test/scroll-trace.test.ts@@ -0,0 +1,380 @@+import { describe, expect, it } from "vitest"+import baseline from "./fixtures/message-scroll-baseline.json"+import {+ classifyTracePair,+ coalesceWriterCalls,+ nativeMargin,+ summarizeScrollTrace,+ validateScrollTrace,+ type ScrollTraceFrame,+ type ScrollTraceResult,+ type ScrollTraceWrite,+} from "./e2e-ui/_fixtures/scroll-trace"++function frame(input: Partial<ScrollTraceFrame> & { frame: number; scrollTop: number }): ScrollTraceFrame {+ return {+ timestamp: input.frame * 16,+ scrollHeight: 1000,+ clientHeight: 400,+ browserMax: 600,+ distanceToEnd: 600 - input.scrollTop,+ programmaticScrollInProgress: false,+ scrollerRect: {+ x: 300,+ y: 50,+ width: 900,+ height: 400,+ top: 50,+ right: 1200,+ bottom: 450,+ left: 300,+ },+ contentRect: null,+ composerRect: null,+ accessoryRailRect: null,+ tailGap: 0,+ newDividerRect: null,+ loaders: {+ top: { mounted: false, loading: false, rect: null },+ bottom: { mounted: false, loading: false, rect: null },+ },+ pill: { mode: null, count: 0, label: null },+ renderedRange: [0, 2],+ visibleRange: [0, 2],+ firstVisibleId: "m1",+ firstVisibleOffset: 4,+ lastVisibleId: "m3",+ domIds: ["m1", "m2", "m3"],+ rows: [],+ mark: "final-stimulus",+ writerRevision: 0,+ measurementRevision: 0,+ ...input,+ }+}++function result(overrides: Partial<ScrollTraceResult> = {}): ScrollTraceResult {+ return {+ schemaVersion: 1,+ scenario: "upward",+ commandDirection: "backward",+ identity: {+ sourceSha: "a".repeat(40),+ lockHash: "b".repeat(64),+ servedBuildId: "build-1",+ probeHash: "c".repeat(64),+ profileVersion: "message-scroll-v1",+ runtime: "chromium",+ account: "alice",+ channel: "channel-1",+ viewport: { width: 1280, height: 800, dpr: 1 },+ },+ startedAt: 0,+ endedAt: 80,+ status: "stable",+ capabilities: {},+ marks: [+ {+ timestamp: 0,+ frame: 1,+ name: "analysis-start:upward",+ dataTransitionSource: null,+ detail: null,+ preEventDistanceToEnd: 0,+ programmaticScrollInProgress: false,+ },+ {+ timestamp: 64,+ frame: 4,+ name: "analysis-end:upward",+ dataTransitionSource: null,+ detail: null,+ preEventDistanceToEnd: 44,+ programmaticScrollInProgress: false,+ },+ {+ timestamp: 64,+ frame: 4,+ name: "final-stimulus",+ dataTransitionSource: null,+ detail: null,+ preEventDistanceToEnd: 44,+ programmaticScrollInProgress: false,+ },+ ],+ frames: [+ frame({ frame: 1, scrollTop: 600 }),+ frame({ frame: 2, scrollTop: 576 }),+ frame({ frame: 3, scrollTop: 580 }),+ frame({ frame: 4, scrollTop: 556, firstVisibleOffset: 3 }),+ ],+ writes: [write({ frame: 2 })],+ measurements: [{ timestamp: 1, frame: 2, id: "m1", index: 1, height: 20 }],+ externalEvents: [+ { timestamp: 0, type: "wheel", detail: { x: 0, y: -24 } },+ { timestamp: 24, type: "wheel", detail: { x: 0, y: -24 } },+ ],+ dropped: { frames: 0, writes: 0 },+ ...overrides,+ }+}++function write(input: Partial<ScrollTraceWrite> = {}): ScrollTraceWrite {+ return {+ timestamp: 1,+ frame: 1,+ method: "scrollTop",+ args: [1],+ mark: "receive",+ fingerprint: "abc",+ stack: "use-scroll-anchor.ts",+ ...input,+ }+}++describe("scroll trace normalization", () => {+ it("accepts explicit stable and timeout results and rejects malformed evidence", () => {+ expect(validateScrollTrace(result())).toEqual([])+ expect(validateScrollTrace(result({ status: "settlementTimedOut" }))).toEqual([])+ expect(validateScrollTrace(result({+ schemaVersion: 2,+ marks: [],+ frames: [frame({ frame: 1, scrollTop: Number.NaN })],+ }))).toEqual(expect.arrayContaining([+ "schema version",+ "final-stimulus mark",+ "analysis window",+ "non-finite geometry",+ ]))+ expect(validateScrollTrace(result({+ externalEvents: [{ timestamp: 1, type: "cookie", detail: "secret" }],+ }))).toContain("sensitive field")+ expect(validateScrollTrace(result({+ externalEvents: [{ timestamp: 1, type: "keydown", detail: "private draft text" }],+ }))).toContain("unsafe key detail")+ expect(validateScrollTrace(result({+ externalEvents: [{ timestamp: 1, type: "keydown", detail: "printable" }],+ }))).not.toContain("unsafe key detail")+ })++ it("keeps metric margins in their native units", () => {+ expect(nativeMargin(10, "css-px")).toBe(1)+ expect(nativeMargin(100, "css-px")).toBe(5)+ expect(nativeMargin(21, "count")).toBe(2)+ expect(nativeMargin(4, "ms")).toBe(1)+ expect(nativeMargin(1, "percentage-point")).toBe(0.1)+ })++ it("keeps the committed baseline observational, unit-correct, and free of user data", () => {+ expect(baseline.schemaVersion).toBe(1)+ expect(baseline.capture.successfulMatrixRuns).toBeGreaterThanOrEqual(2)+ expect(baseline.capture.portablePerformanceGate).toBe(false)+ expect(baseline.units.analysisFrameCount).toBe("count")+ expect(baseline.units.frameDelta).toBe("css-px")+ expect(baseline.units.writerCount).toBe("count")+ expect(baseline.gatePolicy.diagnostic).toEqual(expect.arrayContaining([+ "writer ownership and contention",+ "frame-delta p95 and max",+ ]))+ expect(Object.keys(baseline.observations)).toHaveLength(6)+ expect(JSON.stringify(baseline)).not.toMatch(/account|channel|message(Id|Body)|cookie|authorization/i)+ })+})++describe("scroll trace writers and metrics", () => {+ it("coalesces one logical writer across adjacent microtask and RAF calls", () => {+ const calls = coalesceWriterCalls([+ write({ frame: 4 }),+ write({ frame: 5, method: "scrollTo" }),+ write({ frame: 8, fingerprint: "other", stack: "virtual-core/index.js" }),+ ])+ expect(calls).toHaveLength(2)+ expect(calls[0]).toMatchObject({ owner: "scroll-anchor", firstFrame: 4, lastFrame: 5 })+ expect(calls[0]?.calls).toHaveLength(2)+ expect(calls[1]?.owner).toBe("tanstack-virtual")+ })++ it("keeps known product symptoms diagnostic in the summary", () => {+ const summary = summarizeScrollTrace(result({+ status: "settlementTimedOut",+ writes: [+ write({ frame: 2, stack: "use-scroll-anchor.ts" }),+ write({ frame: 2, fingerprint: "unknown", stack: "bundle.js" }),+ ],+ measurements: [+ { timestamp: 1, frame: 1, id: "m1", index: 1, height: 20 },+ { timestamp: 2, frame: 2, id: "m1", index: 1, height: 21 },+ ],+ }))+ expect(summary.status).toBe("settlementTimedOut")+ expect(summary.finalProgress).toBe(-44)+ expect(summary.reversalCount).toBe(0)+ expect(summary.contentionEpochs).toEqual([{+ frame: 2,+ owners: ["scroll-anchor", "unknown:unknown"],+ }])+ expect(summary.unknownWriterCount).toBe(1)+ expect(summary.repeatedMeasurementRows).toEqual([{ id: "m1", count: 2 }])+ })++ it("summarizes the named action window when the action precedes final settlement", () => {+ const summary = summarizeScrollTrace(result({+ marks: [+ {+ timestamp: 0,+ frame: 1,+ name: "analysis-start:wheel",+ dataTransitionSource: null,+ detail: null,+ preEventDistanceToEnd: 0,+ programmaticScrollInProgress: false,+ },+ {+ timestamp: 48,+ frame: 3,+ name: "analysis-end:wheel",+ dataTransitionSource: null,+ detail: null,+ preEventDistanceToEnd: 40,+ programmaticScrollInProgress: false,+ },+ {+ timestamp: 64,+ frame: 4,+ name: "final-stimulus",+ dataTransitionSource: null,+ detail: null,+ preEventDistanceToEnd: 40,+ programmaticScrollInProgress: false,+ },+ ],+ frames: [+ frame({ frame: 1, scrollTop: 600 }),+ frame({ frame: 2, scrollTop: 576 }),+ frame({ frame: 3, scrollTop: 560 }),+ frame({ frame: 4, scrollTop: 560 }),+ ],+ }))+ expect(summary.settlementFrames).toBe(1)+ expect(summary.analysisFrameCount).toBe(3)+ expect(summary.finalProgress).toBe(-40)+ expect(summary.analysisSegments).toEqual([+ expect.objectContaining({ name: "wheel", frameCount: 3, finalProgress: -40 }),+ ])+ })++ it("keeps multiple composer lanes as separate analysis segments", () => {+ const summary = summarizeScrollTrace(result({+ marks: [+ { timestamp: 0, frame: 1, name: "analysis-start:manual-clear", dataTransitionSource: null, detail: null, preEventDistanceToEnd: 0, programmaticScrollInProgress: false },+ { timestamp: 32, frame: 2, name: "analysis-end:manual-clear", dataTransitionSource: null, detail: null, preEventDistanceToEnd: 20, programmaticScrollInProgress: false },+ { timestamp: 48, frame: 3, name: "analysis-start:accepted-send", dataTransitionSource: null, detail: null, preEventDistanceToEnd: 20, programmaticScrollInProgress: false },+ { timestamp: 64, frame: 4, name: "analysis-end:accepted-send", dataTransitionSource: null, detail: null, preEventDistanceToEnd: 0, programmaticScrollInProgress: false },+ { timestamp: 64, frame: 4, name: "final-stimulus", dataTransitionSource: null, detail: null, preEventDistanceToEnd: 0, programmaticScrollInProgress: false },+ ],+ }))+ expect(summary.analysisSegments.map((segment) => segment.name)).toEqual([+ "manual-clear",+ "accepted-send",+ ])+ expect(summary.analysisSegments.map((segment) => segment.finalProgress)).toEqual([-24, -24])+ })++ it("aggregates every segment while counting reversals only with a local direction", () => {+ const summary = summarizeScrollTrace(result({+ commandDirection: "backward",+ marks: [+ { timestamp: 0, frame: 1, name: "analysis-start:setup", dataTransitionSource: null, detail: { commandDirection: null }, preEventDistanceToEnd: 0, programmaticScrollInProgress: false },+ { timestamp: 32, frame: 2, name: "analysis-end:setup", dataTransitionSource: null, detail: null, preEventDistanceToEnd: 0, programmaticScrollInProgress: false },+ { timestamp: 48, frame: 3, name: "analysis-start:upward", dataTransitionSource: null, detail: { commandDirection: "backward" }, preEventDistanceToEnd: 0, programmaticScrollInProgress: false },+ { timestamp: 64, frame: 4, name: "analysis-end:upward", dataTransitionSource: null, detail: null, preEventDistanceToEnd: 0, programmaticScrollInProgress: false },+ { timestamp: 64, frame: 4, name: "final-stimulus", dataTransitionSource: null, detail: null, preEventDistanceToEnd: 0, programmaticScrollInProgress: false },+ ],+ frames: [+ frame({ frame: 1, scrollTop: 300 }),+ frame({ frame: 2, scrollTop: 600 }),+ frame({ frame: 3, scrollTop: 500 }),+ frame({ frame: 4, scrollTop: 520 }),+ ],+ }))+ expect(summary.analysisSegments.map((segment) => ({+ name: segment.name,+ direction: segment.commandDirection,+ reversals: segment.reversalCount,+ }))).toEqual([+ { name: "setup", direction: null, reversals: 0 },+ { name: "upward", direction: "backward", reversals: 1 },+ ])+ expect(summary.finalProgress).toBe(320)+ expect(summary.reversalCount).toBe(1)+ })+})++describe("matched Web and Desktop classification", () => {+ it("requires complete identity equality before platform attribution", () => {+ const web = result()+ const desktop = result({+ identity: { ...web.identity, runtime: "tauri", servedBuildId: "other" },+ })+ expect(classifyTracePair(web, desktop)).toEqual({+ classification: "unclassified",+ reasons: ["identity:servedBuildId"],+ })+ })++ it("uses unit-correct count and pixel margins only on matched pairs", () => {+ const web = result()+ const desktop = result({+ identity: { ...web.identity, runtime: "tauri" },+ frames: [+ frame({ frame: 1, scrollTop: 600, firstVisibleOffset: 4 }),+ frame({ frame: 2, scrollTop: 576, firstVisibleOffset: 4 }),+ frame({ frame: 3, scrollTop: 590, firstVisibleOffset: 8 }),+ frame({ frame: 4, scrollTop: 556, firstVisibleOffset: 8 }),+ ],+ })+ expect(classifyTracePair(web, desktop).classification).toBe("platform-regression")+ })++ it("rejects same-runtime and missing matched evidence", () => {+ const web = result()+ expect(classifyTracePair(web, result()).reasons).toContain("runtime:desktop")+ const desktop = result({+ identity: { ...web.identity, runtime: "tauri" },+ frames: web.frames.map((value) => ({ ...value, scrollerRect: null })),+ externalEvents: [],+ writes: [],+ measurements: [],+ })+ expect(classifyTracePair(web, desktop)).toEqual({+ classification: "unclassified",+ reasons: [+ "matched-evidence:scroller",+ "matched-evidence:input-cadence",+ "matched-evidence:writer-sequence",+ "matched-evidence:measurement-sequence",+ ],+ })+ })++ it("rejects mismatched scroller, cadence, writer, and measurement sequences", () => {+ const web = result()+ const desktop = result({+ identity: { ...web.identity, runtime: "tauri" },+ frames: web.frames.map((value) => ({+ ...value,+ scrollerRect: value.scrollerRect ? { ...value.scrollerRect, width: 899 } : null,+ })),+ externalEvents: [+ { timestamp: 0, type: "wheel", detail: { x: 0, y: -24 } },+ { timestamp: 40, type: "wheel", detail: { x: 0, y: -24 } },+ ],+ writes: [write({ frame: 2, method: "scrollTo" })],+ measurements: [{ timestamp: 1, frame: 2, id: "m1", index: 1, height: 21 }],+ })+ expect(classifyTracePair(web, desktop)).toEqual({+ classification: "unclassified",+ reasons: ["scroller:width", "input-cadence", "writer-sequence", "measurement-sequence"],+ })+ })+})