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
fix(web): stabilize dynamic message geometry (#696)
Genera2a3084dfb9e
diff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.cssindex 39834bbe7..49f4a1387 100644--- a/src/web/src/app/globals.css+++ b/src/web/src/app/globals.css@@ -2435,6 +2435,21 @@ html.dark .blog-content [data-rehype-pretty-code-figure] span {color: var(--shiki-dark) !important;}+/* Community Markdown images keep Streamdown's wrapper/actions while matching+ the 300px attachment cap. Width remains responsive and intrinsic ratio wins. */+[data-community-message-body] [data-streamdown="image-wrapper"] {+ max-width: 100%;+}++[data-community-message-body] [data-streamdown="image"] {+ display: block;+ width: auto;+ height: auto;+ max-width: 100%;+ max-height: 18.75rem;+ object-fit: contain;+}+/* ── Streamdown code block: everything inside the dark area ── *//* Outer container: owns border + radius + clipping */diff --git a/src/web/src/components/community/messages/attachment-layout.ts b/src/web/src/components/community/messages/attachment-layout.tsindex 5bc1dc597..e674bfab1 100644--- a/src/web/src/components/community/messages/attachment-layout.ts+++ b/src/web/src/components/community/messages/attachment-layout.ts@@ -4,3 +4,16 @@ export function attachmentAspectRatio(): string {return width && height ? `${width}/${height}` : "auto"}++export function attachmentImageFrameStyle(+ width: number | undefined,+ height: number | undefined,+): { width: string; aspectRatio: string } | undefined {+ if (!width || !height || width <= 0 || height <= 0) return undefined+ const constrainedWidth = Math.min(width, 300 * width / height)+ const roundedWidth = Math.round(constrainedWidth * 1000) / 1000+ return {+ width: `min(100%, ${roundedWidth}px)`,+ aspectRatio: `${width}/${height}`,+ }+}diff --git a/src/web/src/components/community/messages/message-body.test.ts b/src/web/src/components/community/messages/message-body.test.tsindex 6596e84db..4578aa3f9 100644--- a/src/web/src/components/community/messages/message-body.test.ts+++ b/src/web/src/components/community/messages/message-body.test.ts@@ -1,8 +1,13 @@import { describe, it, expect, vi } from "vitest"import React from "react"import TestRenderer, { act } from "react-test-renderer"+import { readFileSync } from "node:fs"+import { dirname, resolve } from "node:path"+import { fileURLToPath } from "node:url"import { MessageBody } from "./message-body"+const componentDirectory = dirname(fileURLToPath(import.meta.url))+describe("MessageBody — plain URL rendering", () => {it("renders an unsupported HTTPS URL as a generic clickable link badge", () => {let renderer: TestRenderer.ReactTestRenderer@@ -57,6 +62,28 @@ describe("MessageBody — theme contrast", () => {})})+describe("MessageBody — remote image geometry", () => {+ it("keeps Streamdown's native image wrapper and download control", () => {+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(+ React.createElement(MessageBody, { text: "" }),+ )+ })++ expect(renderer!.root.findAllByProps({ "data-streamdown": "image-wrapper" })).toHaveLength(1)+ const image = renderer!.root.findByProps({ "data-streamdown": "image" })+ act(() => image.props.onLoad({}))+ expect(renderer!.root.findByProps({ title: "Download image" }).type).toBe("button")+ })++ it("caps community Markdown images at 300px without distorting their ratio", () => {+ const css = readFileSync(resolve(componentDirectory, "../../../app/globals.css"), "utf8")+ expect(css).toContain('[data-community-message-body] [data-streamdown="image-wrapper"]')+ expect(css).toMatch(/\[data-community-message-body\] \[data-streamdown="image"\][^{]*\{[^}]*width: auto;[^}]*height: auto;[^}]*max-width: 100%;[^}]*max-height: 18\.75rem;[^}]*object-fit: contain;/s)+ })+})+// Regression test for the bug MD_LITERAL_TAGS included "spoiler" fixed:// Streamdown's `literalTagContent` flattens every descendant of a listed// tag into one text node. `mention`/`channelref` are leaf nodes so that'sdiff --git a/src/web/src/components/community/messages/message.render.test.ts b/src/web/src/components/community/messages/message.render.test.tsindex f8feaba2b..1c6b89325 100644--- a/src/web/src/components/community/messages/message.render.test.ts+++ b/src/web/src/components/community/messages/message.render.test.ts@@ -1266,12 +1266,14 @@ describe("Message image attachment layout", () => {const image = renderer!.root.findByType("img")expect(image.props.src).toBe("/portrait.png")expect(image.props).toMatchObject({ width: 396, height: 702 })- expect(image.props.className).toContain("h-auto")- expect(image.props.className).toContain("w-auto")- expect(image.props.className).toContain("max-h-75")- expect(image.props.className).toContain("max-w-full")- expect(image.parent?.props.className).toContain("w-fit")+ expect(image.props.className).toContain("size-full")+ expect(image.props.className).toContain("absolute")+ expect(image.parent?.props.className).toContain("relative")expect(image.parent?.props.className).toContain("max-w-full")+ expect(image.parent?.props.style).toEqual({+ width: "min(100%, 169.231px)",+ aspectRatio: "396/702",+ })})it("loads the canonical thumbnail in-list and opens the original identity on click", () => {diff --git a/src/web/src/components/community/messages/message.test.ts b/src/web/src/components/community/messages/message.test.tsindex 1498744d4..64c5cd90f 100644--- a/src/web/src/components/community/messages/message.test.ts+++ b/src/web/src/components/community/messages/message.test.ts@@ -1,5 +1,5 @@import { describe, it, expect } from "vitest"-import { attachmentAspectRatio } from "./attachment-layout"+import { attachmentAspectRatio, attachmentImageFrameStyle } from "./attachment-layout"// Reserves the correct CSS aspect-ratio box for an image attachment before// it decodes, mirroring the pattern the embed-image `<img>` already uses.@@ -22,3 +22,31 @@ describe("attachmentAspectRatio", () => {expect(attachmentAspectRatio(undefined, undefined)).toBe("auto")})})++describe("attachmentImageFrameStyle", () => {+ it("reserves a 300px square for a larger square image", () => {+ expect(attachmentImageFrameStyle(512, 512)).toEqual({+ width: "min(100%, 300px)",+ aspectRatio: "512/512",+ })+ })++ it("caps a portrait by height and preserves its ratio", () => {+ expect(attachmentImageFrameStyle(396, 702)).toEqual({+ width: "min(100%, 169.231px)",+ aspectRatio: "396/702",+ })+ })++ it("keeps a small known-size image at intrinsic width", () => {+ expect(attachmentImageFrameStyle(120, 80)).toEqual({+ width: "min(100%, 120px)",+ aspectRatio: "120/80",+ })+ })++ it("keeps legacy incomplete dimensions on intrinsic fallback", () => {+ expect(attachmentImageFrameStyle(undefined, 80)).toBeUndefined()+ expect(attachmentImageFrameStyle(120, undefined)).toBeUndefined()+ })+})diff --git a/src/web/src/components/community/messages/message.tsx b/src/web/src/components/community/messages/message.tsxindex 5537df32b..fe966f9eb 100644--- a/src/web/src/components/community/messages/message.tsx+++ b/src/web/src/components/community/messages/message.tsx@@ -28,7 +28,7 @@ import { avatarInitial } from "@/lib/community/avatar"import { stripInlineMarkup } from "@alook/shared"import type { FileAttachment, ImagePreview, RenderMsg } from "@/lib/community/models/message"import type { OpenProfile } from "@/components/community/social/profile-types"-import { attachmentAspectRatio } from "./attachment-layout"+import { attachmentAspectRatio, attachmentImageFrameStyle } from "./attachment-layout"import { AttachmentCard } from "./attachment-card"import { displayReplyContent } from "@/lib/community/reply-content"import {@@ -690,31 +690,37 @@ function MessageImpl({{m.attachments && (<div className="mt-2 flex flex-col gap-2 pb-2">{m.attachments.map((a, i) => {- if (a.kind === "image") return (- <button- key={i}- onClick={() => onPreviewImage?.({- originalUrl: a.url,- thumbnailUrl: a.thumbnailUrl,- name: a.name,- width: a.width,- height: a.height,- })}- className="block w-fit max-w-full overflow-hidden rounded-lg border border-border transition-colors hover:border-primary/40"- >- <img- data-testid={tid.messageImage(m.id, i)}- src={a.thumbnailUrl ?? a.url}- alt={a.name}- width={a.width}- height={a.height}- className="block h-auto w-auto max-h-75 max-w-full rounded-lg object-contain"- style={{ aspectRatio: attachmentAspectRatio(a.width, a.height) }}- onLoad={onImageLoad}- loading="lazy"- />- </button>- )+ if (a.kind === "image") {+ const frameStyle = attachmentImageFrameStyle(a.width, a.height)+ return (+ <button+ key={i}+ onClick={() => onPreviewImage?.({+ originalUrl: a.url,+ thumbnailUrl: a.thumbnailUrl,+ name: a.name,+ width: a.width,+ height: a.height,+ })}+ className={`${frameStyle ? "relative" : "w-fit"} block max-w-full overflow-hidden rounded-lg border border-border transition-colors hover:border-primary/40`}+ style={frameStyle}+ >+ <img+ data-testid={tid.messageImage(m.id, i)}+ src={a.thumbnailUrl ?? a.url}+ alt={a.name}+ width={a.width}+ height={a.height}+ className={frameStyle+ ? "absolute inset-0 block size-full rounded-lg object-contain"+ : "block h-auto w-auto max-h-75 max-w-full rounded-lg object-contain"}+ style={frameStyle ? undefined : { aspectRatio: attachmentAspectRatio(a.width, a.height) }}+ onLoad={onImageLoad}+ loading="lazy"+ />+ </button>+ )+ }return <AttachmentCard key={i} attachment={a} onPreview={onPreviewAttachment} />})}</div>diff --git a/src/web/src/components/community/messages/thread-opener.test.ts b/src/web/src/components/community/messages/thread-opener.test.tsindex 614830539..724d412ac 100644--- a/src/web/src/components/community/messages/thread-opener.test.ts+++ b/src/web/src/components/community/messages/thread-opener.test.ts@@ -136,12 +136,14 @@ describe("ThreadOpener image attachment layout", () => {const image = renderer!.root.findByType("img")expect(image.props.src).toBe("/portrait.png")expect(image.props).toMatchObject({ width: 396, height: 702 })- expect(image.props.className).toContain("h-auto")- expect(image.props.className).toContain("w-auto")- expect(image.props.className).toContain("max-h-75")- expect(image.props.className).toContain("max-w-full")- expect(image.parent?.props.className).toContain("w-fit")+ expect(image.props.className).toContain("size-full")+ expect(image.props.className).toContain("absolute")+ expect(image.parent?.props.className).toContain("relative")expect(image.parent?.props.className).toContain("max-w-full")+ expect(image.parent?.props.style).toEqual({+ width: "min(100%, 169.231px)",+ aspectRatio: "396/702",+ })})it("uses thumbnailUrl for the list image and passes the original on click", () => {diff --git a/src/web/src/components/community/messages/thread-opener.tsx b/src/web/src/components/community/messages/thread-opener.tsxindex dab6152d9..2db11e2fb 100644--- a/src/web/src/components/community/messages/thread-opener.tsx+++ b/src/web/src/components/community/messages/thread-opener.tsx@@ -3,7 +3,7 @@import { MessagesSquare, ArrowUpRight } from "lucide-react"import { Avatar } from "../avatar"import { MessageBody } from "./message-body"-import { attachmentAspectRatio } from "./attachment-layout"+import { attachmentAspectRatio, attachmentImageFrameStyle } from "./attachment-layout"import { formatMessageTime } from "@/lib/community/format-time"import { Skeleton } from "@/components/ui/skeleton"import { avatarInitial } from "@/lib/community/avatar"@@ -154,30 +154,36 @@ export function ThreadOpener({{msg.attachments && msg.attachments.length > 0 && (<div className="mt-2 flex flex-col gap-2 pb-2">{msg.attachments.map((a, i) => {- if (a.kind === "image") return (- <button- key={i}- onClick={() => onPreviewImage?.({- originalUrl: a.url,- thumbnailUrl: a.thumbnailUrl,- name: a.name,- width: a.width,- height: a.height,- })}- className="block w-fit max-w-full overflow-hidden rounded-lg border border-border transition-colors hover:border-primary/40"- >- <img- data-testid={tid.threadOpenerImage(i)}- src={a.thumbnailUrl ?? a.url}- alt={a.name}- width={a.width}- height={a.height}- className="block h-auto w-auto max-h-75 max-w-full rounded-lg object-contain"- style={{ aspectRatio: attachmentAspectRatio(a.width, a.height) }}- loading="lazy"- />- </button>- )+ if (a.kind === "image") {+ const frameStyle = attachmentImageFrameStyle(a.width, a.height)+ return (+ <button+ key={i}+ onClick={() => onPreviewImage?.({+ originalUrl: a.url,+ thumbnailUrl: a.thumbnailUrl,+ name: a.name,+ width: a.width,+ height: a.height,+ })}+ className={`${frameStyle ? "relative" : "w-fit"} block max-w-full overflow-hidden rounded-lg border border-border transition-colors hover:border-primary/40`}+ style={frameStyle}+ >+ <img+ data-testid={tid.threadOpenerImage(i)}+ src={a.thumbnailUrl ?? a.url}+ alt={a.name}+ width={a.width}+ height={a.height}+ className={frameStyle+ ? "absolute inset-0 block size-full rounded-lg object-contain"+ : "block h-auto w-auto max-h-75 max-w-full rounded-lg object-contain"}+ style={frameStyle ? undefined : { aspectRatio: attachmentAspectRatio(a.width, a.height) }}+ loading="lazy"+ />+ </button>+ )+ }return <AttachmentCard key={i} attachment={a} onPreview={onPreviewAttachment} />})}</div>diff --git a/src/web/src/hooks/community/use-scroll-anchor.repin.test.ts b/src/web/src/hooks/community/use-scroll-anchor.repin.test.tsindex f670a6238..b196c7728 100644--- a/src/web/src/hooks/community/use-scroll-anchor.repin.test.ts+++ b/src/web/src/hooks/community/use-scroll-anchor.repin.test.ts@@ -11,6 +11,7 @@ import type { FlatItem } from "@/lib/community/message-list-items"let refs: Array<{ current: unknown }> = []let refIndex = 0let layoutEffects: Array<() => void | (() => void)> = []+let resizeCallbacks: ResizeObserverCallback[] = []vi.mock("react", () => ({useRef: (initial: unknown) => {@@ -45,33 +46,73 @@ function resetHarness() {refs = []refIndex = 0layoutEffects = []+ resizeCallbacks = []virtualizerOptions = undefinedvirtualizer.options.anchorTo = "end"virtualizer.isAtEnd.mockReturnValue(true)virtualizer.scrollToEnd.mockReset()virtualizer.scrollToIndex.mockReset()+ vi.stubGlobal("ResizeObserver", class {+ constructor(callback: ResizeObserverCallback) {+ resizeCallbacks.push(callback)+ }++ observe() {}+ unobserve() {}+ disconnect() {}+ })}-async function mountHook() {+async function mountHook({+ distanceToEnd = 0,+ initialClientHeight = 800,+ initialScrollHeight = 1_600,+ items = [] as FlatItem[],+ initialScrollReady = false,+ heroMeasured = false,+ hasMoreNewer,+ presentVersion,+ viewerUserId,+}: {+ distanceToEnd?: number+ initialClientHeight?: number+ initialScrollHeight?: number+ items?: FlatItem[]+ initialScrollReady?: boolean+ heroMeasured?: boolean+ hasMoreNewer?: boolean+ presentVersion?: number+ viewerUserId?: string+} = {}) {const { useScrollAnchor } = await import("./use-scroll-anchor")+ const hookInput = {+ items,+ initialScrollReady,+ heroHeight: 0,+ heroMeasured,+ hasMoreNewer,+ presentVersion,+ viewerUserId,+ }// The React module is intentionally mocked above; this calls a deterministic// hook shim rather than mounting a real component tree.// eslint-disable-next-line react-hooks/rules-of-hooks- const result = useScrollAnchor({- items: [] as FlatItem[],- initialScrollReady: false,- heroHeight: 0,- heroMeasured: false,- })+ const result = useScrollAnchor(hookInput)const listeners = new Map<string, EventListener>()const scrollWrites: number[] = []- let scrollTop = 0+ let clientHeight = initialClientHeight+ let scrollHeight = initialScrollHeight+ let scrollTop = Math.max(0, scrollHeight - clientHeight - distanceToEnd)const scroller = {- scrollHeight: 1_600,- clientHeight: 800,addEventListener: (type: string, listener: EventListener) => listeners.set(type, listener),removeEventListener: vi.fn(),+ get clientHeight() {+ return clientHeight+ },+ get scrollHeight() {+ return scrollHeight+ },get scrollTop() {return scrollTop},@@ -81,10 +122,75 @@ async function mountHook() {},} as unknown as HTMLDivElementresult.scrollRef.current = scroller+ virtualizer.scrollToEnd.mockImplementation(() => {+ scrollTop = Math.max(0, scrollHeight - clientHeight)+ })- // The first layout effect installs the real scroll/wheel intent listeners.- layoutEffects[0]?.()- return { listeners, scrollWrites, scroller }+ const runLayoutEffects = () => {+ for (const effect of layoutEffects) effect()+ }+ runLayoutEffects()++ const rerender = (overrides: Partial<typeof hookInput>) => {+ refIndex = 0+ layoutEffects = []+ Object.assign(hookInput, overrides)+ // eslint-disable-next-line react-hooks/rules-of-hooks+ const nextResult = useScrollAnchor(hookInput)+ nextResult.scrollRef.current = scroller+ runLayoutEffects()+ return nextResult+ }++ const setBrowserScrollTop = (value: number) => {+ scrollTop = Math.max(0, Math.min(value, scrollHeight - clientHeight))+ }+ const setScrollHeight = (value: number) => {+ scrollHeight = value+ setBrowserScrollTop(scrollTop)+ }+ const setClientHeight = (value: number) => {+ clientHeight = value+ // Browser max-scroll clamping is not a JavaScript policy write.+ setBrowserScrollTop(scrollTop)+ }+ const dispatchScroll = () => listeners.get("scroll")?.(new Event("scroll"))+ const dispatchResize = () => resizeCallbacks.at(-1)?.([], {} as ResizeObserver)+ const resizeViewport = (+ nextClientHeight: number,+ order: "scroll-ro" | "ro-scroll" = "ro-scroll",+ ) => {+ setClientHeight(nextClientHeight)+ if (order === "scroll-ro") {+ dispatchScroll()+ dispatchResize()+ } else {+ dispatchResize()+ dispatchScroll()+ }+ }+ const geometry = () => ({ clientHeight, scrollHeight, scrollTop })++ return {+ listeners,+ scrollWrites,+ scroller,+ result,+ dispatchScroll,+ resizeViewport,+ setBrowserScrollTop,+ setScrollHeight,+ geometry,+ rerender,+ }+}++function messageItem(id: string, authorId?: string): FlatItem {+ return {+ kind: "message",+ m: { id, type: "chat", grouped: false, authorId },+ key: `msg:${id}`,+ }}function growingRow(requestFrame: (callback: FrameRequestCallback) => void) {@@ -159,13 +265,203 @@ describe("useScrollAnchor delayed row-growth re-pin", () => {const adjust = virtualizer.shouldAdjustScrollPositionOnItemSizeChangeexpect(adjust).toBeTypeOf("function")- expect(adjust!({} as never, 20, {} as never)).toBe(false)+ expect(adjust!(+ { key: "unmeasured", start: 0, end: 20 } as never,+ 20,+ {+ itemSizeCache: new Map(),+ scrollAdjustments: 0,+ scrollDirection: null,+ scrollOffset: 40,+ } as never,+ )).toBe(false)virtualizer.isAtEnd.mockReturnValue(true)listeners.get("scroll")?.(new Event("scroll"))+ expect(virtualizer.options.anchorTo).toBe("start")++ scroller.scrollTop = scroller.scrollHeight+ listeners.get("scroll")?.(new Event("scroll"))expect(virtualizer.options.anchorTo).toBe("end")listeners.get("keydown")?.({ key: "PageUp" } as KeyboardEvent)expect(virtualizer.options.anchorTo).toBe("start")})})++const EXACT_PIN_BOUNDARIES = [0, 1, 2, 99, 100, 101, 300]++describe("useScrollAnchor viewport resize exact-pinned latch", () => {+ it.each(EXACT_PIN_BOUNDARIES)(+ "uses the resize end writer only for an initial %ipx distance when the viewport grows",+ async (distanceToEnd) => {+ const { resizeViewport } = await mountHook({ distanceToEnd })++ resizeViewport(799)++ expect(virtualizer.scrollToEnd).toHaveBeenCalledTimes(distanceToEnd <= 1 ? 1 : 0)+ },+ )++ it.each(EXACT_PIN_BOUNDARIES)(+ "uses the resize end writer only for an initial %ipx distance when the viewport shrinks",+ async (distanceToEnd) => {+ const { resizeViewport } = await mountHook({ distanceToEnd })++ resizeViewport(801)++ expect(virtualizer.scrollToEnd).toHaveBeenCalledTimes(distanceToEnd <= 1 ? 1 : 0)+ },+ )++ it("promotes false only after a stable scroll moves toward the literal end", async () => {+ const { dispatchScroll, geometry, resizeViewport, setBrowserScrollTop } = await mountHook({+ distanceToEnd: 2,+ })++ setBrowserScrollTop(geometry().scrollHeight - geometry().clientHeight)+ dispatchScroll()+ resizeViewport(799)++ expect(virtualizer.scrollToEnd).toHaveBeenCalledTimes(1)+ })++ it("does not promote false when content shrink reaches 1px at the same scrollTop", async () => {+ const { dispatchScroll, geometry, resizeViewport, setScrollHeight } = await mountHook({+ distanceToEnd: 2,+ })++ setScrollHeight(geometry().scrollHeight - 1)+ dispatchScroll()+ resizeViewport(799)++ expect(virtualizer.scrollToEnd).not.toHaveBeenCalled()+ })++ it("clears exact-pinned immediately on existing upward wheel and keyboard intent", async () => {+ const wheel = await mountHook({ distanceToEnd: 0 })+ wheel.listeners.get("wheel")?.({ deltaY: -1 } as WheelEvent)+ wheel.resizeViewport(799)+ expect(virtualizer.scrollToEnd).not.toHaveBeenCalled()++ resetHarness()+ const keyboard = await mountHook({ distanceToEnd: 0 })+ keyboard.listeners.get("keydown")?.({ key: "PageUp" } as KeyboardEvent)+ keyboard.resizeViewport(799)+ expect(virtualizer.scrollToEnd).not.toHaveBeenCalled()+ })++ it.each(["scroll-ro", "ro-scroll"] as const)(+ "keeps a clamped false latch false through a second resize for %s ordering",+ async (order) => {+ const { resizeViewport } = await mountHook({ distanceToEnd: 2 })++ // Growing the viewport by 3px clamps the browser scrollTop down to its+ // new max. Whether that scroll callback runs before or after RO, it must+ // not turn the original 2px-away latch true.+ resizeViewport(803, order)+ resizeViewport(799, "ro-scroll")++ expect(virtualizer.scrollToEnd).not.toHaveBeenCalled()+ },+ )++ it.each([+ { name: "grow→grow", heights: [780, 760] },+ { name: "shrink→shrink", heights: [801, 802] },+ { name: "grow→shrink", heights: [780, 800] },+ ])("preserves a false latch across rapid $name viewport sequences", async ({ heights }) => {+ const { resizeViewport } = await mountHook({ distanceToEnd: 2 })++ for (const height of heights) resizeViewport(height)++ expect(virtualizer.scrollToEnd).not.toHaveBeenCalled()+ })++ it("keeps an exact-pinned latch continuous across rapid grow and shrink", async () => {+ const { resizeViewport } = await mountHook({ distanceToEnd: 1 })++ resizeViewport(780)+ resizeViewport(760)+ resizeViewport(800)++ expect(virtualizer.scrollToEnd).toHaveBeenCalledTimes(3)+ })++ it("lets the existing explicit end action restore the latch", async () => {+ const { resizeViewport, result } = await mountHook({ distanceToEnd: 300 })++ result.scrollToBottom()+ virtualizer.scrollToEnd.mockClear()+ resizeViewport(799)++ expect(virtualizer.scrollToEnd).toHaveBeenCalledTimes(1)+ })++ it("restores the latch for warm-mount and peer-follow end actions", async () => {+ const first = messageItem("m1", "peer")+ const { rerender, resizeViewport } = await mountHook({+ distanceToEnd: 2,+ items: [first],+ heroMeasured: true,+ })++ expect(virtualizer.scrollToEnd).toHaveBeenCalledTimes(1)+ expect(virtualizer.options.anchorTo).toBe("end")++ virtualizer.scrollToEnd.mockClear()+ rerender({+ items: [first, messageItem("m2", "peer")],+ viewerUserId: "viewer",+ })+ expect(virtualizer.scrollToEnd).toHaveBeenCalledTimes(1)+ expect(virtualizer.options.anchorTo).toBe("end")++ virtualizer.scrollToEnd.mockClear()+ resizeViewport(799)+ expect(virtualizer.scrollToEnd).toHaveBeenCalledTimes(1)+ })++ it("restores the latch for an explicit present action", async () => {+ const { resizeViewport } = await mountHook({+ distanceToEnd: 300,+ items: [messageItem("m1")],+ presentVersion: 1,+ })++ expect(virtualizer.scrollToEnd).toHaveBeenCalledTimes(1)+ expect(virtualizer.options.anchorTo).toBe("end")++ virtualizer.scrollToEnd.mockClear()+ resizeViewport(799)+ expect(virtualizer.scrollToEnd).toHaveBeenCalledTimes(1)+ })++ it("re-pins an exactly pinned image load but ignores one after upward intent", async () => {+ const { listeners, result } = await mountHook({ distanceToEnd: 0 })++ virtualizer.options.anchorTo = "start"+ result.onImageLoad()+ expect(virtualizer.options.anchorTo).toBe("end")+ expect(virtualizer.scrollToEnd).toHaveBeenCalledTimes(1)++ virtualizer.scrollToEnd.mockClear()+ listeners.get("wheel")?.({ deltaY: -1 } as WheelEvent)+ result.onImageLoad()+ expect(virtualizer.options.anchorTo).toBe("start")+ expect(virtualizer.scrollToEnd).not.toHaveBeenCalled()+ })++ it("uses exact-pinned rather than 100px near-bottom for delayed row growth", async () => {+ const { scrollWrites } = await mountHook({ distanceToEnd: 99 })+ const row = growingRow(() => {})+ const measure = virtualizerOptions?.measureElement++ expect(measure!(row.element, undefined, virtualizer as never)).toBe(400)+ row.growTo(500)+ expect(measure!(row.element, undefined, virtualizer as never)).toBe(500)+ await Promise.resolve()++ expect(scrollWrites).toEqual([])+ })+})diff --git a/src/web/src/hooks/community/use-scroll-anchor.test.ts b/src/web/src/hooks/community/use-scroll-anchor.test.tsindex 41ab2dba4..617a9424b 100644--- a/src/web/src/hooks/community/use-scroll-anchor.test.ts+++ b/src/web/src/hooks/community/use-scroll-anchor.test.ts@@ -308,16 +308,30 @@ describe("shouldAdjustMessageScrollPosition", () => {expect(shouldAdjustMessageScrollPosition(item, 96, instance({ scrollDirection: "backward" }))).toBe(false)})- it("does not compensate later row growth after the viewer deliberately leaves the bottom", () => {+ it("compensates a measured row wholly above an away viewport", () => {const measured = new Map([[item.key, item.size]])expect(shouldAdjustMessageScrollPosition(item,240,instance({ itemSizeCache: measured }),true,+ )).toBe(true)+ })++ it("does not compensate a measured row intersecting an away viewport", () => {+ const measured = new Map([[item.key, item.size]])+ expect(shouldAdjustMessageScrollPosition(+ { ...item, end: 1_040 },+ 240,+ instance({ itemSizeCache: measured }),+ true,)).toBe(false)})+ it("does not compensate an estimate-to-measure pass after the viewer leaves the bottom", () => {+ expect(shouldAdjustMessageScrollPosition(item, 96, instance(), true)).toBe(false)+ })+it("keeps first-measurement compensation above the fold while idle or scrolling forward", () => {expect(shouldAdjustMessageScrollPosition(item, 96, instance())).toBe(true)expect(shouldAdjustMessageScrollPosition(item, 96, instance({ scrollDirection: "forward" }))).toBe(true)diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.tsindex 10dd6d73a..28dbc1984 100644--- a/src/web/src/hooks/community/use-scroll-anchor.ts+++ b/src/web/src/hooks/community/use-scroll-anchor.ts@@ -79,8 +79,10 @@ type SizeAdjustmentVirtualizer = {* input — visible as the NEW-divider view shuddering and refusing to move.** Re-measurements retain the library's narrower "entirely above the fold"- * rule, and forward/idle first measurements retain the original rule, so- * image growth, prepend anchoring, and normal downward navigation keep their+ * rule even after the viewer leaves the bottom. That is not a bottom re-pin:+ * it offsets growth above the viewport so the visible reading anchor stays+ * put. Forward/idle first measurements retain the original rule, so image+ * growth, prepend anchoring, and normal downward navigation keep their* existing compensation behavior.*/export function shouldAdjustMessageScrollPosition(@@ -89,11 +91,9 @@ export function shouldAdjustMessageScrollPosition(instance: SizeAdjustmentVirtualizer,userScrolledAway = false,): boolean {- if (userScrolledAway) return false- if (instance.scrollDirection === "backward") return false-const offset = (instance.scrollOffset ?? 0) + instance.scrollAdjustmentsconst isFirstMeasure = !instance.itemSizeCache.has(item.key)+ if (isFirstMeasure && (userScrolledAway || instance.scrollDirection === "backward")) return falsereturn isFirstMeasure ? item.start < offset : item.end <= offset}@@ -427,9 +427,15 @@ export function useScrollAnchor({const messages = extractScrollAnchorMessages(items)const tailId = messages[messages.length - 1]?.id ?? nullconst wasAtEndRef = useRef(true)+ const wasExactlyPinnedRef = useRef(true)const userScrolledAwayRef = useRef(false)+ const acceptedClientHeightRef = useRef(0)+ const acceptedScrollTopRef = useRef(0)const measuredRowHeightsRef = useRef(new WeakMap<Element, number>())const bottomRepinQueuedRef = useRef(false)+ const liveResizeAnchor = wasExactlyPinnedRef.current && !userScrolledAwayRef.current+ ? "end"+ : "start"// eslint-disable-next-line react-hooks/incompatible-library -- library limitation, same as member-list.tsxconst virtualizer = useVirtualizer({@@ -454,7 +460,7 @@ export function useScrollAnchor({// By the time ResizeObserver calls us, an overflowing child can have// already increased the browser scrollHeight without emitting a// scroll event, making a formerly pinned viewport appear far away.- && wasAtEndRef.current+ && wasExactlyPinnedRef.current&& !userScrolledAwayRef.current&& !bottomRepinQueuedRef.current) {@@ -519,10 +525,10 @@ export function useScrollAnchor({// distance excludes `scrollMargin` (the hero) while its scroll offset// includes it, so a viewer who moved upward by less than the hero height can// be mistaken for still-at-end and yanked down by the resize delta. Switch- // only that between-render mode to `start` once the user has moved away;- // the next render's `setOptions({ anchorTo: "end" })` still performs prepend- // anchoring before this assignment restores the live resize mode.- virtualizer.options.anchorTo = userScrolledAwayRef.current ? "start" : "end"+ // only that between-render mode to `start` once the exact-pinned latch is+ // false; the next render's `setOptions({ anchorTo: "end" })` still performs+ // prepend anchoring before this assignment restores the live resize mode.+ virtualizer.options.anchorTo = liveResizeAnchor// Whether the viewer was within NEAR_BOTTOM_PX of the end BEFORE this// commit's append — the semantics `decideScrollAction` documents for its@@ -538,7 +544,12 @@ export function useScrollAnchor({useLayoutEffect(() => {const el = scrollRef.currentif (!el) return- let lastScrollTop = el.scrollTop+ acceptedClientHeightRef.current = el.clientHeight+ acceptedScrollTopRef.current = el.scrollTop+ wasExactlyPinnedRef.current = Math.max(+ 0,+ el.scrollHeight - el.clientHeight - el.scrollTop,+ ) <= 1const onScroll = () => {const nextScrollTop = el.scrollTopconst isAtEnd = virtualizer.isAtEnd(NEAR_BOTTOM_PX)@@ -547,20 +558,40 @@ export function useScrollAnchor({if (isAtEnd) {userScrolledAwayRef.current = falsevirtualizer.options.anchorTo = "end"- } else if (leftEnd || nextScrollTop < lastScrollTop - 1) {+ } else if (leftEnd || nextScrollTop < acceptedScrollTopRef.current - 1) {userScrolledAwayRef.current = truevirtualizer.options.anchorTo = "start"}- lastScrollTop = nextScrollTop++ // A scroll dispatched while the viewport height differs from the last+ // ResizeObserver sample belongs to that pending resize. It cannot tell+ // us whether the viewer was exactly pinned before layout changed.+ if (el.clientHeight === acceptedClientHeightRef.current) {+ const distanceToEnd = Math.max(0, el.scrollHeight - el.clientHeight - nextScrollTop)+ if (distanceToEnd > 1 || nextScrollTop < acceptedScrollTopRef.current - 1) {+ wasExactlyPinnedRef.current = false+ } else if (nextScrollTop > acceptedScrollTopRef.current) {+ // False may only recover from a real, stable scroll toward the end.+ // Same-position or decreasing browser-clamp events at the end must+ // preserve false for the next resize.+ wasExactlyPinnedRef.current = true+ }+ acceptedScrollTopRef.current = nextScrollTop+ }+ virtualizer.options.anchorTo = wasExactlyPinnedRef.current && !userScrolledAwayRef.current+ ? "end"+ : "start"}const onWheel = (event: WheelEvent) => {if (event.deltaY < 0) {+ wasExactlyPinnedRef.current = falseuserScrolledAwayRef.current = truevirtualizer.options.anchorTo = "start"}}const onKeyDown = (event: KeyboardEvent) => {if (["ArrowUp", "PageUp", "Home"].includes(event.key)) {+ wasExactlyPinnedRef.current = falseuserScrolledAwayRef.current = truevirtualizer.options.anchorTo = "start"}@@ -595,11 +626,15 @@ export function useScrollAnchor({if (idx !== null) {virtualizer.scrollToIndex(idx, { align: "center" })} else {+ wasExactlyPinnedRef.current = true+ virtualizer.options.anchorTo = "end"virtualizer.scrollToEnd()}return}case "scrollToEnd":+ wasExactlyPinnedRef.current = true+ virtualizer.options.anchorTo = "end"virtualizer.scrollToEnd()returncase "none":@@ -622,7 +657,9 @@ export function useScrollAnchor({lastTailId: tailId,}wasAtEndRef.current = true+ wasExactlyPinnedRef.current = trueuserScrolledAwayRef.current = false+ virtualizer.options.anchorTo = "end"virtualizer.scrollToEnd()}, [hasMoreNewer, presentVersion, tailId, virtualizer])@@ -650,30 +687,32 @@ export function useScrollAnchor({// changes and the bottom-pinned content (`min-h-full … justify-end`) would// otherwise appear to jump. A `ResizeObserver` on the viewport itself// catches every such resize regardless of cause without coupling to the- // composer component: if the list was at the bottom, re-pin instantly (NOT- // the smooth `scrollToBottom` — a smooth animation firing on every- // keystroke resize is janky and fights rapid successive resizes); otherwise- // compensate `scrollTop` by the height delta so the visible top-of-content- // stays put. Keyed on `clientHeight`, orthogonal to the hero compensation- // below (keyed on `heroHeight`) — separate effects, no double-apply.- const prevClientHeightRef = useRef(0)+ // composer component. Only a viewport that was literally pinned within+ // 1px re-pins instantly (NOT the smooth `scrollToBottom` — a smooth+ // animation firing on every keystroke resize is janky and fights rapid+ // successive resizes). Every away position is left to the browser; in+ // particular, the resize policy never writes a compensating height delta.+ // Keyed on `clientHeight`, orthogonal to the hero compensation above (keyed+ // on `heroHeight`) — separate effects, no double-apply.useLayoutEffect(() => {const el = scrollRef.currentif (!el) return// First-fire guard: ResizeObserver fires immediately on observe() with// the current size. Seed the previous height first so that initial// callback computes a zero delta instead of a spurious jump at mount.- prevClientHeightRef.current = el.clientHeight+ acceptedClientHeightRef.current = el.clientHeight+ acceptedScrollTopRef.current = el.scrollTopconst ro = new ResizeObserver(() => {- const prev = prevClientHeightRef.current+ const prev = acceptedClientHeightRef.currentconst next = el.clientHeightif (next === prev) return- const wasAtEnd = virtualizer.isAtEnd(NEAR_BOTTOM_PX)- prevClientHeightRef.current = next- if (wasAtEnd) {+ const wasExactlyPinned = wasExactlyPinnedRef.current+ acceptedClientHeightRef.current = next+ acceptedScrollTopRef.current = el.scrollTop+ if (wasExactlyPinned && !userScrolledAwayRef.current) {+ wasExactlyPinnedRef.current = true+ virtualizer.options.anchorTo = "end"virtualizer.scrollToEnd()- } else {- el.scrollTop += prev - next}})ro.observe(el)@@ -696,18 +735,24 @@ export function useScrollAnchor({const scrollToBottom = useCallback(() => {userScrolledAwayRef.current = falsewasAtEndRef.current = true+ wasExactlyPinnedRef.current = true+ virtualizer.options.anchorTo = "end"virtualizer.scrollToEnd({ behavior: "smooth" })}, [virtualizer])// Re-pin after an attachment image finishes loading, but only if the- // viewer is still at/near the bottom — restores the deleted+ // viewer was exactly pinned before that growth — restores the deleted// `watchAsyncGrowth` image-decode re-scroll narrowly, per-image and gated,// so a dimensionless image that grows after `scrollToEnd` already fired// still lands the message's bottom at the viewport bottom, while never- // yanking a reader who has scrolled away. Instant (no smooth) so it doesn't- // animate on every image load.+ // yanking a reader even 2px away. Instant (no smooth) so it doesn't animate+ // on every image load.const onImageLoad = useCallback(() => {- if (virtualizer.isAtEnd(NEAR_BOTTOM_PX)) virtualizer.scrollToEnd()+ if (wasExactlyPinnedRef.current && !userScrolledAwayRef.current) {+ wasExactlyPinnedRef.current = true+ virtualizer.options.anchorTo = "end"+ virtualizer.scrollToEnd()+ }}, [virtualizer])const jumpTo = useCallback((messageId: string, behavior: ScrollBehavior = "smooth") => {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.tsindex a6a46ddd6..64d5b2cd5 100644--- 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.ts@@ -18,6 +18,7 @@ import {markScrollTrace,scrollTraceSelfTest,startScrollTrace,+ summarizeScrollTrace,type ScrollTraceResult,} from "./_fixtures/scroll-trace"import { tid } from "./_fixtures/testids"@@ -190,6 +191,18 @@ async function establishScrollDistancePrecondition(return geometry}+async function establishExactPinnedPrecondition(+ scroller: Locator,+ label: string,+ targetDistanceToEnd: 0 | 1,+): Promise<{ scrollTop: number; scrollHeight: number; clientHeight: number; distanceToEnd: number }> {+ // The resize latch is intentionally monotonic: same-position/clamp events+ // at the end cannot recover false. Exercise its one valid recovery path by+ // first establishing away geometry, then scrolling forward into <=1px.+ await establishScrollDistancePrecondition(scroller, `${label}-away-first`, 8)+ return establishScrollDistancePrecondition(scroller, label, targetDistanceToEnd)+}+async function establishMidHistoryPrecondition(scroller: Locator,): Promise<{ scrollTop: number; scrollHeight: number; clientHeight: number; distanceToEnd: number }> {@@ -235,6 +248,99 @@ async function establishMidHistoryPrecondition(return readGeometry()}+type MessageViewportGeometry = {+ scrollTop: number+ scrollHeight: number+ clientHeight: number+ distanceToEnd: number+ firstVisibleId: string | null+ firstVisibleOffset: number | null+ contentPaddingBottom: number+ railPosition: string | null+ railRect: { top: number; bottom: number } | null+ scrollerRect: { top: number; bottom: number }+}++async function readMessageViewportGeometry(scroller: Locator): Promise<MessageViewportGeometry> {+ return scroller.evaluate((element, accessoryRailTestId) => {+ const root = element as HTMLElement+ const rootRect = root.getBoundingClientRect()+ const firstVisible = Array.from(root.querySelectorAll<HTMLElement>("[data-msg-id]"))+ .find((row) => {+ const rect = row.getBoundingClientRect()+ return rect.bottom > rootRect.top + 1 && rect.top < rootRect.bottom - 1+ }) ?? null+ const firstRect = firstVisible?.getBoundingClientRect() ?? null+ const content = root.querySelector<HTMLElement>("[data-message-list-content]")+ const rail = root.querySelector<HTMLElement>(`[data-testid="${accessoryRailTestId}"]`)+ const railRect = rail?.getBoundingClientRect() ?? null+ return {+ scrollTop: root.scrollTop,+ scrollHeight: root.scrollHeight,+ clientHeight: root.clientHeight,+ distanceToEnd: Math.max(0, root.scrollHeight - root.clientHeight - root.scrollTop),+ firstVisibleId: firstVisible?.dataset.msgId ?? null,+ firstVisibleOffset: firstRect ? firstRect.top - rootRect.top : null,+ contentPaddingBottom: content ? Number.parseFloat(getComputedStyle(content).paddingBottom) : 0,+ railPosition: rail ? getComputedStyle(rail).position : null,+ railRect: railRect ? { top: railRect.top, bottom: railRect.bottom } : null,+ scrollerRect: { top: rootRect.top, bottom: rootRect.bottom },+ }+ }, tid.composerAccessoryRail)+}++async function waitForCommittedGeometry(scroller: Locator): Promise<MessageViewportGeometry> {+ await scroller.evaluate(() => new Promise<void>((resolveValue) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolveValue()))+ }))+ let previous = ""+ let settled: MessageViewportGeometry | null = null+ await expect.poll(async () => {+ const geometry = await readMessageViewportGeometry(scroller)+ const signature = JSON.stringify(geometry)+ const stable = signature === previous+ previous = signature+ if (stable) settled = geometry+ return stable+ }, { timeout: 20_000 }).toBe(true)+ return settled!+}++async function advanceScrollTraceFrame(scroller: Locator): Promise<void> {+ await scroller.evaluate(() => new Promise<void>((resolveValue) => {+ requestAnimationFrame(() => resolveValue())+ }))+}++function expectAwayAnchorPreserved(+ before: MessageViewportGeometry,+ after: MessageViewportGeometry,+ label: string,+): void {+ expect(Math.abs(after.scrollTop - before.scrollTop), `${label}: scrollTop`).toBeLessThanOrEqual(1)+ expect(after.firstVisibleId, `${label}: first visible row`).toBe(before.firstVisibleId)+ expect(+ Math.abs((after.firstVisibleOffset ?? 0) - (before.firstVisibleOffset ?? 0)),+ `${label}: first visible offset`,+ ).toBeLessThanOrEqual(1)+}++function expectAwayLatchPreserved(+ after: MessageViewportGeometry,+ label: string,+): void {+ expect(after.distanceToEnd, `${label}: remains away`).toBeGreaterThan(1)+}++function expectFixedMessageGeometry(geometry: MessageViewportGeometry, label: string): void {+ expect(geometry.contentPaddingBottom, `${label}: desktop tail safe area`).toBe(72)+ if (geometry.railRect) {+ expect(geometry.railPosition, `${label}: rail position`).toBe("absolute")+ expect(geometry.railRect.top, `${label}: rail top`).toBeGreaterThanOrEqual(geometry.scrollerRect.top - 1)+ expect(geometry.railRect.bottom, `${label}: rail bottom`).toBeLessThanOrEqual(geometry.scrollerRect.bottom + 1)+ }+}+function messageCreateCount(frames: Awaited<ReturnType<typeof proxyCommunityWebSockets>>["frames"],channelId: string,@@ -663,6 +769,203 @@ test.describe.serial("message scroll characterization", () => {expect(messageCreateCount(proxy.frames, composerChannelId, awaySend)).toBe(1)})+ test("exact-pinned composer and accessory resizes preserve geometry boundaries", async ({ asUser }, testInfo) => {+ test.setTimeout(180_000)+ const alice = await asUser("alice")+ const bob = await asUser("bob")+ await alice.page.setViewportSize(VIEWPORT)+ await bob.page.setViewportSize(VIEWPORT)+ await installScrollTrace(alice.page)+ const proxy = await proxyCommunityWebSockets(alice.context)+ let mutationPosts = 0+ alice.page.on("request", (request) => {+ const pathname = new URL(request.url()).pathname+ if (+ request.method() === "POST"+ && (pathname.endsWith("/messages") || pathname.includes("/attachments"))+ ) mutationPosts += 1+ })+ await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${composerChannelId}`)+ await gotoAfterUserWsAuth(bob.page, `/c/channels/${serverId}/${composerChannelId}`)+ const scroller = alice.page.getByTestId(tid.messageScroller)+ const editable = composerEditable(alice.page)+ const bobEditable = composerEditable(bob.page)+ await expect(editable).toBeVisible()+ await expect(bobEditable).toBeVisible()+ await startScrollTrace(alice.page, {+ scenario: "composer-exact-pinned-resize-policy",+ identity: identity(composerChannelId),+ estimatedSizes: composerProfile.estimates,+ })++ const composerLines = (prefix: string, count: number) => Array.from(+ { length: count },+ (_, line) => `${prefix} line ${line} ${"content ".repeat(8)}`,+ ).join("\n")++ for (const distance of [0, 1, 2, 99, 100, 101, 300]) {+ await editable.fill("")+ const precondition = distance <= 1+ ? await establishExactPinnedPrecondition(+ scroller,+ `composer-resize-${distance}`,+ distance as 0 | 1,+ )+ : await establishScrollDistancePrecondition(+ scroller,+ `composer-resize-${distance}`,+ distance,+ )+ await markScrollTrace(alice.page, `composer-resize-${distance}-precondition`, {+ detail: precondition,+ })+ const before = await waitForCommittedGeometry(scroller)+ expectFixedMessageGeometry(before, `resize-${distance}-before`)++ await beginScrollTraceAnalysis(alice.page, `composer-grow-${distance}`)+ await editable.fill(composerLines(`boundary-${distance}`, 6))+ await expect.poll(() => scroller.evaluate((element) => element.clientHeight))+ .toBeLessThan(before.clientHeight)+ const grown = await waitForCommittedGeometry(scroller)+ expectFixedMessageGeometry(grown, `resize-${distance}-grown`)+ if (distance <= 1) {+ expect(grown.distanceToEnd, `resize-${distance}-grown pinned`).toBeLessThanOrEqual(1)+ } else {+ expectAwayAnchorPreserved(before, grown, `resize-${distance}-grown away`)+ }+ await endScrollTraceAnalysis(alice.page, `composer-grow-${distance}`)+ await advanceScrollTraceFrame(scroller)++ await beginScrollTraceAnalysis(alice.page, `composer-shrink-${distance}`)+ await editable.fill("")+ await expect.poll(() => scroller.evaluate((element) => element.clientHeight))+ .toBeGreaterThan(grown.clientHeight)+ const shrunk = await waitForCommittedGeometry(scroller)+ expectFixedMessageGeometry(shrunk, `resize-${distance}-shrunk`)+ if (distance <= 1) {+ expect(shrunk.distanceToEnd, `resize-${distance}-shrunk pinned`).toBeLessThanOrEqual(1)+ } else {+ expectAwayAnchorPreserved(before, shrunk, `resize-${distance}-shrunk away`)+ }+ await endScrollTraceAnalysis(alice.page, `composer-shrink-${distance}`)+ await advanceScrollTraceFrame(scroller)+ }++ const rapidPrecondition = await establishScrollDistancePrecondition(scroller, "rapid-resize-away", 2)+ await markScrollTrace(alice.page, "rapid-resize-away-precondition", { detail: rapidPrecondition })+ await beginScrollTraceAnalysis(alice.page, "rapid-composer-resizes")+ const rapidBase = await waitForCommittedGeometry(scroller)+ await editable.fill(composerLines("rapid-small", 2))+ const rapidGrowOne = await waitForCommittedGeometry(scroller)+ await editable.fill(composerLines("rapid-large", 6))+ const rapidGrowTwo = await waitForCommittedGeometry(scroller)+ await editable.fill(composerLines("rapid-small", 2))+ const rapidShrinkOne = await waitForCommittedGeometry(scroller)+ await editable.fill("")+ const rapidShrinkTwo = await waitForCommittedGeometry(scroller)+ expect(rapidGrowOne.clientHeight).toBeLessThan(rapidBase.clientHeight)+ expect(rapidGrowTwo.clientHeight).toBeLessThan(rapidGrowOne.clientHeight)+ expect(rapidShrinkOne.clientHeight).toBeGreaterThan(rapidGrowTwo.clientHeight)+ expect(rapidShrinkTwo.clientHeight).toBeGreaterThan(rapidShrinkOne.clientHeight)+ for (const [label, geometry] of [+ ["grow-one", rapidGrowOne],+ ["grow-two", rapidGrowTwo],+ ["shrink-one", rapidShrinkOne],+ ["shrink-two", rapidShrinkTwo],+ ] as const) {+ expectAwayLatchPreserved(geometry, `rapid-${label}`)+ expectFixedMessageGeometry(geometry, `rapid-${label}`)+ }+ await endScrollTraceAnalysis(alice.page, "rapid-composer-resizes")+ await advanceScrollTraceFrame(scroller)++ await establishExactPinnedPrecondition(scroller, "reply-resize-pinned", 0)+ const replyBase = await waitForCommittedGeometry(scroller)+ await beginScrollTraceAnalysis(alice.page, "reply-banner-pinned")+ const replyTarget = scroller.locator("[data-msg-id]").last()+ const replyTargetBox = await replyTarget.boundingBox()+ expect(replyTargetBox).not.toBeNull()+ await alice.page.mouse.move(+ replyTargetBox!.x + replyTargetBox!.width / 2,+ replyTargetBox!.y + replyTargetBox!.height / 2,+ )+ const replyButton = replyTarget.getByRole("button", { name: "Reply" })+ await expect(replyButton).toBeVisible()+ await expect(replyButton).toBeInViewport()+ expect((await waitForCommittedGeometry(scroller)).distanceToEnd).toBeLessThanOrEqual(1)+ await replyButton.click()+ await expect(alice.page.locator('[data-slot="composer-reply-preview"]')).toBeVisible()+ const replyOpen = await waitForCommittedGeometry(scroller)+ expect(replyOpen.clientHeight).toBeLessThan(replyBase.clientHeight)+ expect(replyOpen.distanceToEnd).toBeLessThanOrEqual(1)+ expectFixedMessageGeometry(replyOpen, "reply-open")+ await alice.page.getByRole("button", { name: "Cancel reply" }).click()+ await expect(alice.page.locator('[data-slot="composer-reply-preview"]')).toHaveCount(0)+ const replyClosed = await waitForCommittedGeometry(scroller)+ expect(replyClosed.clientHeight).toBe(replyBase.clientHeight)+ expect(replyClosed.distanceToEnd).toBeLessThanOrEqual(1)+ await endScrollTraceAnalysis(alice.page, "reply-banner-pinned")+ await advanceScrollTraceFrame(scroller)++ await establishScrollDistancePrecondition(scroller, "attachment-resize-away", 300)+ const attachmentBase = await waitForCommittedGeometry(scroller)+ await beginScrollTraceAnalysis(alice.page, "attachment-chip-away")+ await alice.page.getByTestId(tid.composerFileInput).setInputFiles({+ name: "geometry-only.txt",+ mimeType: "text/plain",+ buffer: Buffer.from("geometry only"),+ })+ await expect(alice.page.getByText("geometry-only.txt", { exact: true })).toBeVisible()+ const attachmentOpen = await waitForCommittedGeometry(scroller)+ expect(attachmentOpen.clientHeight).toBeLessThan(attachmentBase.clientHeight)+ expectAwayAnchorPreserved(attachmentBase, attachmentOpen, "attachment-open-away")+ expectFixedMessageGeometry(attachmentOpen, "attachment-open-away")+ await alice.page.getByRole("button", { name: "Remove file" }).click()+ await expect(alice.page.getByText("geometry-only.txt", { exact: true })).toHaveCount(0)+ const attachmentClosed = await waitForCommittedGeometry(scroller)+ expect(attachmentClosed.clientHeight).toBe(attachmentBase.clientHeight)+ expectAwayAnchorPreserved(attachmentBase, attachmentClosed, "attachment-closed-away")+ await endScrollTraceAnalysis(alice.page, "attachment-chip-away")+ await advanceScrollTraceFrame(scroller)++ await establishScrollDistancePrecondition(scroller, "typing-rail-away", 101)+ const typingBase = await waitForCommittedGeometry(scroller)+ await beginScrollTraceAnalysis(alice.page, "typing-rail-away")+ await bobEditable.fill("typing rail geometry")+ await expect(alice.page.getByTestId(tid.typingIndicator)).toBeVisible({ timeout: 20_000 })+ const typingOpen = await waitForCommittedGeometry(scroller)+ expect(typingOpen.clientHeight).toBe(typingBase.clientHeight)+ expectAwayAnchorPreserved(typingBase, typingOpen, "typing-rail-away")+ expectFixedMessageGeometry(typingOpen, "typing-rail-away")+ await bobEditable.fill("")+ await endScrollTraceAnalysis(alice.page, "typing-rail-away")+ await advanceScrollTraceFrame(scroller)++ const trace = await finishAndAttach(alice.page, testInfo)+ const resizeSegments = new Map(+ summarizeScrollTrace(trace).analysisSegments.map((segment) => [segment.name, segment]),+ )+ for (const distance of [0, 1, 2, 99, 100, 101, 300]) {+ const grow = resizeSegments.get(`composer-grow-${distance}`)+ const shrink = resizeSegments.get(`composer-shrink-${distance}`)+ expect(grow, `missing composer-grow-${distance}`).toBeDefined()+ expect(shrink, `missing composer-shrink-${distance}`).toBeDefined()+ if (distance <= 1) {+ expect(grow!.writerCount, `composer-grow-${distance} writer`).toBeGreaterThanOrEqual(1)+ expect(shrink!.writerCount, `composer-shrink-${distance} writer`).toBeGreaterThanOrEqual(1)+ } else {+ expect(grow!.writerCount, `composer-grow-${distance} writer`).toBe(0)+ expect(shrink!.writerCount, `composer-shrink-${distance} writer`).toBe(0)+ }+ }+ expect(resizeSegments.get("rapid-composer-resizes")?.writerCount).toBe(0)+ expect(resizeSegments.get("attachment-chip-away")?.writerCount).toBe(0)+ expect(resizeSegments.get("typing-rail-away")?.writerCount).toBe(0)+ expect(mutationPosts).toBe(0)+ expect(proxy.frames.flatMap(communityFrameEvents).filter((event) =>+ event.type === "community:message.create" && event.channelId === composerChannelId)).toHaveLength(0)+ })+test.afterEach(async ({ page }) => {await abortScrollTrace(page)})diff --git a/src/web/src/test/fixtures/message-scroll-baseline.json b/src/web/src/test/fixtures/message-scroll-baseline.jsonindex dc8f88d03..ad4467d6e 100644--- a/src/web/src/test/fixtures/message-scroll-baseline.json+++ b/src/web/src/test/fixtures/message-scroll-baseline.json@@ -2,9 +2,9 @@"schemaVersion": 1,"profileVersion": "message-scroll-v1","sourceIdentity": {- "sourceSha": "6396fe02a061f960b67516a5a0446bfb82514cdf",- "lockHash": "691443b5cbe8fffe73b061fc23209b82d1cfd5884c125b5c3aafb03fb86bbe93",- "servedBuildId": "6396fe02a061f960b67516a5a0446bfb82514cdf:691443b5cbe8fffe",+ "sourceSha": "26acaa716584fd2ba84251c43c4699478b9c390c",+ "lockHash": "28616d32a9c5de70229b572f4ec5ab6a1463987461ce504c5cf251882565e3d0",+ "servedBuildId": "26acaa716584fd2ba84251c43c4699478b9c390c:28616d32a9c5de70","probeHash": "12fe64c1db42a698207a426b540e8cea62a2e67c80f9dc245616da3095019289","runtime": "chromium","viewport": {@@ -55,148 +55,290 @@"observations": {"cold-load-and-async-row": {"status": "stable",- "frameCount": 688,- "analysisFrameCount": 684,+ "frameCount": 683,+ "analysisFrameCount": 679,"settlementFrames": 5,"finalProgress": 1623,"reversalCount": 0,"maxReversalPx": 0,- "zeroProgressFrames": 671,- "frameDelta": { "p50": 0, "p95": 0, "max": 495 },+ "zeroProgressFrames": 666,+ "frameDelta": {+ "p50": 0,+ "p95": 0,+ "max": 495+ },"anchorDriftPx": null,"tailGapDriftPx": null,- "writerCount": 31,- "contentionEpochCount": 14,- "unknownWriterCount": 31,+ "writerCount": 30,+ "contentionEpochCount": 13,+ "unknownWriterCount": 30,"measurementCount": 33,- "repeatedMeasurementRowCount": 4,- "maxMeasurementsPerRow": 14,+ "repeatedMeasurementRowCount": 5,+ "maxMeasurementsPerRow": 13,"estimateErrorPx": null,"segments": [- { "name": "cold-load-and-async-row", "commandDirection": null, "frameCount": 684, "finalProgress": 1623, "reversalCount": 0, "maxReversalPx": 0 }+ {+ "name": "cold-load-and-async-row",+ "commandDirection": null,+ "frameCount": 679,+ "finalProgress": 1623,+ "reversalCount": 0,+ "maxReversalPx": 0+ }]},"warm-cache-revalidation": {"status": "stable",- "frameCount": 7,- "analysisFrameCount": 3,+ "frameCount": 8,+ "analysisFrameCount": 4,"settlementFrames": 5,"finalProgress": 0,"reversalCount": 0,"maxReversalPx": 0,- "zeroProgressFrames": 2,- "frameDelta": { "p50": 0, "p95": 0, "max": 0 },+ "zeroProgressFrames": 3,+ "frameDelta": {+ "p50": 0,+ "p95": 0,+ "max": 0+ },"anchorDriftPx": 0,"tailGapDriftPx": 0,"writerCount": 0,"contentionEpochCount": 0,"unknownWriterCount": 0,- "measurementCount": 12,+ "measurementCount": 16,"repeatedMeasurementRowCount": 1,"maxMeasurementsPerRow": 3,- "estimateErrorPx": { "p50": 57.5, "p95": 494, "max": 494 },+ "estimateErrorPx": {+ "p50": 57.5,+ "p95": 494,+ "max": 494+ },"segments": [- { "name": "warm-cache-revalidation", "commandDirection": null, "frameCount": 3, "finalProgress": 0, "reversalCount": 0, "maxReversalPx": 0 }+ {+ "name": "warm-cache-revalidation",+ "commandDirection": null,+ "frameCount": 4,+ "finalProgress": 0,+ "reversalCount": 0,+ "maxReversalPx": 0+ }]},"older-loading-prepend": {"status": "stable",- "frameCount": 48,- "analysisFrameCount": 42,+ "frameCount": 102,+ "analysisFrameCount": 98,"settlementFrames": 5,"finalProgress": -4145,"reversalCount": 1,"maxReversalPx": 77,- "zeroProgressFrames": 39,- "frameDelta": { "p50": 0, "p95": 0, "max": 4222 },+ "zeroProgressFrames": 95,+ "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 },+ "measurementCount": 86,+ "repeatedMeasurementRowCount": 34,+ "maxMeasurementsPerRow": 4,+ "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 }+ {+ "name": "older-loading-prepend",+ "commandDirection": "backward",+ "frameCount": 98,+ "finalProgress": -4145,+ "reversalCount": 1,+ "maxReversalPx": 77+ }]},"newer-loading-present": {"status": "stable",- "frameCount": 99,- "analysisFrameCount": 95,+ "frameCount": 32,+ "analysisFrameCount": 28,"settlementFrames": 5,"finalProgress": 6547,- "reversalCount": 3,+ "reversalCount": 2,"maxReversalPx": 147,- "zeroProgressFrames": 89,- "frameDelta": { "p50": 0, "p95": 60, "max": 5834 },+ "zeroProgressFrames": 22,+ "frameDelta": {+ "p50": 0,+ "p95": 590,+ "max": 5834+ },"anchorDriftPx": null,"tailGapDriftPx": 1537,- "writerCount": 27,- "contentionEpochCount": 4,- "unknownWriterCount": 27,- "measurementCount": 73,- "repeatedMeasurementRowCount": 26,+ "writerCount": 18,+ "contentionEpochCount": 3,+ "unknownWriterCount": 18,+ "measurementCount": 77,+ "repeatedMeasurementRowCount": 28,"maxMeasurementsPerRow": 4,- "estimateErrorPx": { "p50": 33.922, "p95": 158.422, "max": 158.422 },+ "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 }+ {+ "name": "newer-loading-present",+ "commandDirection": "forward",+ "frameCount": 28,+ "finalProgress": 6547,+ "reversalCount": 2,+ "maxReversalPx": 147+ }]},"remote-receive-and-upward-input": {"status": "stable",- "frameCount": 597,- "analysisFrameCount": 557,+ "frameCount": 590,+ "analysisFrameCount": 547,"settlementFrames": 5,- "finalProgress": 7187,- "reversalCount": 0,- "maxReversalPx": 0,- "zeroProgressFrames": 460,- "frameDelta": { "p50": 0, "p95": 24, "max": 3385 },+ "finalProgress": 3208,+ "reversalCount": 1,+ "maxReversalPx": 15,+ "zeroProgressFrames": 465,+ "frameDelta": {+ "p50": 0,+ "p95": 24,+ "max": 3385+ },"anchorDriftPx": 0,- "tailGapDriftPx": -1274.422,- "writerCount": 19,+ "tailGapDriftPx": -1095.422,+ "writerCount": 23,"contentionEpochCount": 1,- "unknownWriterCount": 19,- "measurementCount": 134,- "repeatedMeasurementRowCount": 42,- "maxMeasurementsPerRow": 7,- "estimateErrorPx": { "p50": 33.922, "p95": 158.422, "max": 172.422 },+ "unknownWriterCount": 23,+ "measurementCount": 86,+ "repeatedMeasurementRowCount": 22,+ "maxMeasurementsPerRow": 6,+ "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 }+ {+ "name": "remote-pinned",+ "commandDirection": null,+ "frameCount": 72,+ "finalProgress": 4051,+ "reversalCount": 0,+ "maxReversalPx": 0+ },+ {+ "name": "remote-away-101",+ "commandDirection": null,+ "frameCount": 74,+ "finalProgress": 0,+ "reversalCount": 0,+ "maxReversalPx": 0+ },+ {+ "name": "remote-mid-history-burst",+ "commandDirection": null,+ "frameCount": 135,+ "finalProgress": -15,+ "reversalCount": 0,+ "maxReversalPx": 0+ },+ {+ "name": "remote-during-smooth",+ "commandDirection": "forward",+ "frameCount": 68,+ "finalProgress": 612,+ "reversalCount": 1,+ "maxReversalPx": 15+ },+ {+ "name": "upward-60x24",+ "commandDirection": "backward",+ "frameCount": 198,+ "finalProgress": -1440,+ "reversalCount": 0,+ "maxReversalPx": 0+ }]},"composer-clear-send-and-viewport": {"status": "stable",- "frameCount": 366,- "analysisFrameCount": 180,+ "frameCount": 373,+ "analysisFrameCount": 178,"settlementFrames": 5,- "finalProgress": 235,+ "finalProgress": 355,"reversalCount": 0,"maxReversalPx": 0,- "zeroProgressFrames": 170,- "frameDelta": { "p50": 0, "p95": 0, "max": 339 },+ "zeroProgressFrames": 169,+ "frameDelta": {+ "p50": 0,+ "p95": 0,+ "max": 339+ },"anchorDriftPx": -39,"tailGapDriftPx": 300,- "writerCount": 11,+ "writerCount": 9,"contentionEpochCount": 1,- "unknownWriterCount": 11,+ "unknownWriterCount": 9,"measurementCount": 12,"repeatedMeasurementRowCount": 1,"maxMeasurementsPerRow": 6,- "estimateErrorPx": { "p50": 57.5, "p95": 494, "max": 494 },+ "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 }+ {+ "name": "manual-delete-pinned",+ "commandDirection": null,+ "frameCount": 5,+ "finalProgress": -23,+ "reversalCount": 0,+ "maxReversalPx": 0+ },+ {+ "name": "manual-delete-away",+ "commandDirection": null,+ "frameCount": 6,+ "finalProgress": 0,+ "reversalCount": 0,+ "maxReversalPx": 0+ },+ {+ "name": "optimistic-send-pinned",+ "commandDirection": null,+ "frameCount": 54,+ "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+ }]}}