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): compact token usage and remove stale scroll memory (#628)
Gustavo Yeb6088f06d93b
diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsxindex 7cb0dc145..a32bd0c32 100644--- a/src/web/src/app/c/me/[dmId]/page.tsx+++ b/src/web/src/app/c/me/[dmId]/page.tsx@@ -480,7 +480,6 @@ function DmView() {key={dmId}variant="dm"channel={dm.name}- scrollMemoryKey={`dm:${dmId}`}messages={messages}loading={loadingOwnership.messageBodyLoading}newDividerBefore={newDividerBefore}diff --git a/src/web/src/components/community/bots/bot-token-usage-chart.test.ts b/src/web/src/components/community/bots/bot-token-usage-chart.test.tsindex 53188722c..68f715844 100644--- a/src/web/src/components/community/bots/bot-token-usage-chart.test.ts+++ b/src/web/src/components/community/bots/bot-token-usage-chart.test.ts@@ -9,6 +9,12 @@ vi.mock("@/components/ui/tooltip", () => ({TooltipContent: ({ children }: React.PropsWithChildren) =>React.createElement("tooltip-content", null, children),}))+vi.mock("@/components/ui/popover", () => ({+ Popover: ({ children }: React.PropsWithChildren) => React.createElement(React.Fragment, null, children),+ PopoverTrigger: ({ render }: { render: React.ReactElement }) => React.cloneElement(render),+ PopoverContent: ({ children, className }: React.PropsWithChildren<{ className?: string }>) =>+ React.createElement("popover-content", { className }, children),+}))import {BotTokenUsageChart,@@ -95,8 +101,9 @@ describe("BotTokenUsageChart", () => {expect(targets[6]!.props["aria-label"]).toContain("Output 2")expect(renderer.root.findAll((node) => String(node.props.className).includes("h-10.5"))).not.toHaveLength(0)- expect(text(renderer.root)).not.toContain("8/23")- expect(text(renderer.root)).not.toContain("Today")+ const desktopTargetText = targets.map(text).join(" ")+ expect(desktopTargetText).not.toContain("8/23")+ expect(desktopTargetText).not.toContain("Today")expect(text(renderer.root)).not.toContain("Tokens")})@@ -117,6 +124,29 @@ describe("BotTokenUsageChart", () => {.toHaveLength(0)})+ it("groups seven mobile days into a four-column selector with one pressed 44px target", () => {+ const usage: BotTokenUsage = {+ capability: "supported",+ days: sevenDays(usageDay(+ "2026-08-29",+ { input: complete(8), output: complete(2), cache: complete(0) },+ "in_progress",+ )),+ }+ const renderer = render(usage)+ const mobileTargets = renderer.root.findAll((node) => node.props["aria-pressed"] !== undefined)+ expect(mobileTargets).toHaveLength(7)+ expect(mobileTargets.filter((node) => node.props["aria-pressed"])).toHaveLength(1)+ expect(mobileTargets[6]!.props["aria-pressed"]).toBe(true)+ expect(mobileTargets.every((node) => String(node.props.className).includes("h-11"))).toBe(true)+ expect(String(mobileTargets[0]!.parent?.props.className)).toContain("grid-cols-4")++ act(() => mobileTargets[2]!.props.onClick())+ const updatedTargets = renderer.root.findAll((node) => node.props["aria-pressed"] !== undefined)+ expect(updatedTargets[2]!.props["aria-pressed"]).toBe(true)+ expect(updatedTargets.filter((node) => node.props["aria-pressed"])).toHaveLength(1)+ })+it("omits missing and unsupported usage without reserving a chart slot", () => {const unsupported = render({ capability: "unsupported", days: [] })expect(unsupported.toJSON()).toBeNull()diff --git a/src/web/src/components/community/bots/bot-token-usage-chart.tsx b/src/web/src/components/community/bots/bot-token-usage-chart.tsxindex 9ceeace7a..8b8988c2f 100644--- a/src/web/src/components/community/bots/bot-token-usage-chart.tsx+++ b/src/web/src/components/community/bots/bot-token-usage-chart.tsx@@ -219,7 +219,7 @@ export function BotTokenUsageChart({<div className="text-xs text-foreground"><UsageDayDetail day={usage.days[mobileDayIndex] ?? usage.days.at(-1)!} /></div>- <div className="flex flex-col border-t border-border/60 pt-2">+ <div className="grid grid-cols-4 gap-2 border-t border-border/60 pt-2">{usage.days.map((day, index) => (<buttonkey={day.day}@@ -227,7 +227,7 @@ export function BotTokenUsageChart({data-testid={tid.botUsageDay(botId, day.day)}aria-pressed={index === mobileDayIndex}onClick={() => setMobileDayIndex(index)}- className="flex h-11 items-center rounded-md px-2 text-left text-xs text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"+ className="flex h-11 min-w-11 items-center justify-center rounded-md px-1 text-center text-xs text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none aria-pressed:bg-accent aria-pressed:font-semibold aria-pressed:text-foreground"><span>{dayLabel(day)}</span></button>diff --git a/src/web/src/components/community/channels/text-channel-surface.tsx b/src/web/src/components/community/channels/text-channel-surface.tsxindex b3724335d..bda42a861 100644--- a/src/web/src/components/community/channels/text-channel-surface.tsx+++ b/src/web/src/components/community/channels/text-channel-surface.tsx@@ -11,7 +11,6 @@ import { Composer } from "@/components/community/messages/composer"import { MessageContextSheet } from "@/components/community/messages/message-context-sheet"import { MessageList } from "@/components/community/messages/message-list"import { useAuthorMentionInsertion } from "@/components/community/messages/use-author-mention-insertion"-import { readMessageScrollPosition } from "@/components/community/messages/message-scroll-memory"import {MessageChannelController,} from "@/components/community/messages/message-channel-controller"@@ -71,14 +70,12 @@ export function TextChannelSurface({viewerName: viewer.name,viewerDiscriminator: viewer.discriminator,})- const scrollMemoryKey = `channel:${channelId}`const feed = useChannelMessageFeed({channelId,serverId,viewerUserId: viewer.id,isChildChannel: false,anchorMessageId,- preferCachedWindowOnMount: readMessageScrollPosition(scrollMemoryKey) !== undefined,})useEffect(() => {setRightPanel(null)@@ -119,7 +116,6 @@ export function TextChannelSurface({<MessageListkey={channelId}channel={channelName}- scrollMemoryKey={scrollMemoryKey}messages={feed.messages}loading={feed.isLoading}pinnedIds={controller.pinnedIds}diff --git a/src/web/src/components/community/channels/text-channel-surface.wiring.test.ts b/src/web/src/components/community/channels/text-channel-surface.wiring.test.tsindex 2ebdfcf71..8149ed04a 100644--- a/src/web/src/components/community/channels/text-channel-surface.wiring.test.ts+++ b/src/web/src/components/community/channels/text-channel-surface.wiring.test.ts@@ -57,9 +57,6 @@ vi.mock("@/components/community/messages/use-author-mention-insertion", () => ({insertMentionText: vi.fn(),}),}))-vi.mock("@/components/community/messages/message-scroll-memory", () => ({- readMessageScrollPosition: () => undefined,-}))vi.mock("@/components/community/messages/message-channel-controller", () => ({MessageChannelController: ({ children }: {children: (value: MessageChannelControllerValue) => React.ReactNodediff --git a/src/web/src/components/community/channels/thread-channel-surface.test.ts b/src/web/src/components/community/channels/thread-channel-surface.test.tsindex e2f402e7e..2a45fd933 100644--- a/src/web/src/components/community/channels/thread-channel-surface.test.ts+++ b/src/web/src/components/community/channels/thread-channel-surface.test.ts@@ -260,7 +260,6 @@ describe("ThreadChannelSurface ownership", () => {viewerUserId: "viewer_1",isChildChannel: true,anchorMessageId: "m_target",- preferCachedWindowOnMount: false,})const messageListProps = mockedMessageList.mock.calls.at(-1)![0]const opener = messageListProps.hero as React.ReactElement<React.ComponentProps<typeof ThreadOpener>>diff --git a/src/web/src/components/community/channels/thread-channel-surface.tsx b/src/web/src/components/community/channels/thread-channel-surface.tsxindex 2ce53cf15..27c3dd5a9 100644--- a/src/web/src/components/community/channels/thread-channel-surface.tsx+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx@@ -14,7 +14,6 @@ import { MessageChannelController } from "@/components/community/messages/messagimport { MessageContextSheet } from "@/components/community/messages/message-context-sheet"import { MessageList } from "@/components/community/messages/message-list"import { useAuthorMentionInsertion } from "@/components/community/messages/use-author-mention-insertion"-import { readMessageScrollPosition } from "@/components/community/messages/message-scroll-memory"import { ThreadOpener } from "@/components/community/messages/thread-opener"import type { FileAttachment, ImagePreview } from "@/lib/community/models/message"import type { OpenProfile } from "@/components/community/social/profile-types"@@ -99,14 +98,12 @@ export function ThreadChannelSurface({})const { mutateAsync: editMessageAsync } = useEditMessage()useClaimThreadOpenerReadHandoff(threadOpenerHandoff)- const scrollMemoryKey = `thread:${channelId}`const feed = useChannelMessageFeed({channelId,serverId,viewerUserId: viewer.id,isChildChannel: true,anchorMessageId,- preferCachedWindowOnMount: readMessageScrollPosition(scrollMemoryKey) !== undefined,})const displayName = localName ?? channelName@@ -224,7 +221,6 @@ export function ThreadChannelSurface({<MessageListkey={channelId}channel={displayName}- scrollMemoryKey={scrollMemoryKey}messages={controller.feed.messages}loading={controller.feed.isLoading}pinnedIds={controller.pinnedIds}diff --git a/src/web/src/components/community/messages/message-list-controller.test.ts b/src/web/src/components/community/messages/message-list-controller.test.tsindex 3819d7c28..7bebcd5e8 100644--- a/src/web/src/components/community/messages/message-list-controller.test.ts+++ b/src/web/src/components/community/messages/message-list-controller.test.ts@@ -6,12 +6,6 @@ import TestRenderer, { act } from "react-test-renderer"import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { useMessageListController, type MessageListController } from "./message-list-controller"import type { ResolvedMessageListProps } from "./message-list-types"-import {- clearMessageScrollPositions,- captureActiveMessageScrollPosition,- readMessageScrollPosition,- writeMessageScrollPosition,-} from "./message-scroll-memory"const webRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..")const readWebSource = (path: string) => readFileSync(resolve(webRoot, path), "utf8")@@ -136,7 +130,6 @@ describe("useMessageListController", () => {selectedRowBottom = 20scrollNode.scrollTop = 0scrollNode.clientHeight = 692- clearMessageScrollPositions()heroNode.offsetHeight = 0requestFrame = vi.fn((callback: FrameRequestCallback) => {const id = ++nextFrameId@@ -194,7 +187,6 @@ describe("useMessageListController", () => {viewerUserId: undefined,heroHeight: 0,heroMeasured: false,- restoredScrollTop: undefined,})expect(mocks.sentinelInputs.slice(0, 2)).toEqual([{@@ -260,7 +252,6 @@ describe("useMessageListController", () => {viewerUserId: "viewer_1",heroHeight: 0,heroMeasured: true,- restoredScrollTop: undefined,})expect(mocks.sentinelInputs.slice(-2)).toEqual([{@@ -323,80 +314,6 @@ describe("useMessageListController", () => {expect(disconnect).toHaveBeenCalled()})- it("restores through the virtualizer and captures scroll before route teardown", () => {- writeMessageScrollPosition("channel:one", 2200)- let renderer: TestRenderer.ReactTestRenderer- act(() => {- renderer = TestRenderer.create(- React.createElement(Probe, { value: props({ scrollMemoryKey: "channel:one" }) }),- { createNodeMock },- )- })- expect(mocks.virtualizer.scrollToOffset).toHaveBeenCalledWith(2200, { align: "start" })- scrollNode.scrollTop = 2200- runNextFrame()- runNextFrame()-- scrollNode.scrollTop = 1880- runNextFrame()- expect(scrollNode.scrollTop).toBe(1880)-- act(() => {- renderer!.update(React.createElement(Probe, {- value: props({ scrollMemoryKey: "channel:one" }),- }))- })- expect(mocks.virtualizer.scrollToOffset).toHaveBeenCalledTimes(3)-- act(() => renderer!.unmount())- })-- it("waits through delayed viewport resize compensation before restoring", () => {- writeMessageScrollPosition("channel:one", 2200)- let renderer: TestRenderer.ReactTestRenderer- act(() => {- renderer = TestRenderer.create(- React.createElement(Probe, { value: props({ scrollMemoryKey: "channel:one" }) }),- { createNodeMock },- )- })- scrollNode.scrollTop = 2200- runNextFrame()- runNextFrame()-- // A restored draft can wrap the mobile composer after the first stable- // frames, shrinking the viewport and triggering +24px compensation.- scrollNode.clientHeight = 668- scrollNode.scrollTop = 2224- runNextFrame()- expect(scrollNode.scrollTop).toBe(2200)- runNextFrame()- runNextFrame()- runNextFrame()- runNextFrame()-- act(() => renderer!.unmount())- })-- it("claims an empty scroll key without starting a restore loop", () => {- let renderer: TestRenderer.ReactTestRenderer- act(() => {- renderer = TestRenderer.create(- React.createElement(Probe, { value: props({ scrollMemoryKey: "channel:empty" }) }),- { createNodeMock },- )- })- expect(mocks.virtualizer.scrollToOffset).not.toHaveBeenCalled()-- scrollNode.scrollTop = 1400- captureActiveMessageScrollPosition()- expect(readMessageScrollPosition("channel:empty")).toBe(1400)-- scrollNode.scrollTop = 0- act(() => renderer!.unmount())- expect(readMessageScrollPosition("channel:empty")).toBe(1400)- })-it("combines initial readiness with loaded-target readiness and preserves state across channel-only changes", () => {const consumed = vi.fn()let renderer: TestRenderer.ReactTestRendererdiff --git a/src/web/src/components/community/messages/message-list-controller.ts b/src/web/src/components/community/messages/message-list-controller.tsindex 4a156a40e..033f23fe2 100644--- a/src/web/src/components/community/messages/message-list-controller.ts+++ b/src/web/src/components/community/messages/message-list-controller.ts@@ -6,14 +6,9 @@ import { flattenMessageItems } from "@/lib/community/message-list-items"import { useScrollAnchor } from "@/hooks/community/use-scroll-anchor"import { useVirtualCursorSentinel } from "@/hooks/community/use-virtual-cursor-sentinel"import type { ResolvedMessageListProps } from "./message-list-types"-import {- readMessageScrollPosition,- registerActiveMessageScrollCapture,-} from "./message-scroll-memory"export function useMessageListController({messages,- scrollMemoryKey,loading,newDividerBefore,scrollToMessageId,@@ -87,9 +82,6 @@ export function useMessageListController({const [heroHeight, setHeroHeight] = useState(0)const [heroMeasured, setHeroMeasured] = useState(false)const isLoading = !!loading && messages.length === 0- const rememberedScrollTop = scrollMemoryKey && !scrollToMessageId- ? readMessageScrollPosition(scrollMemoryKey)- : undefineduseEffect(() => {const element = heroRef.currentif (!element) return@@ -120,90 +112,8 @@ export function useMessageListController({viewerUserId,heroHeight,heroMeasured,- restoredScrollTop: rememberedScrollTop,})- const restoredScrollKeyRef = useRef<string | null>(null)- useLayoutEffect(() => {- const element = scrollRef.current- if (!element || !scrollMemoryKey || isLoading) return- if (!scrollAnchorReady || !heroMeasured || scrollToMessageId) return- if (restoredScrollKeyRef.current === scrollMemoryKey) return- const saved = rememberedScrollTop- if (saved === undefined) {- restoredScrollKeyRef.current = scrollMemoryKey- return- }-- let frame = 0- let attempts = 0- let stableFrames = 0- let lastClientHeight = element.clientHeight- let lastScrollHeight = element.scrollHeight- const restore = () => {- const target = Math.min(saved, Math.max(0, element.scrollHeight - element.clientHeight))- virtualizer.scrollToOffset(- target,- { align: "start" },- )- element.scrollTop = target- return target- }- const restoreUntilSettled = () => {- const target = restore()- frame = window.requestAnimationFrame(() => {- attempts += 1- const dimensionsStable = element.clientHeight === lastClientHeight- && element.scrollHeight === lastScrollHeight- const movedAwayFromTarget = Math.abs(element.scrollTop - target) > 1- lastClientHeight = element.clientHeight- lastScrollHeight = element.scrollHeight- // Once layout is stable, an offset change is the viewer taking over- // the viewport. Stop restoring instead of yanking them back to a- // snapshot captured before a same-channel reconnect/remount. A- // composer resize is intentionally different: its dimensions change,- // so the loop still corrects the resulting compensation on the next- // frame.- if (dimensionsStable && movedAwayFromTarget) {- restoredScrollKeyRef.current = scrollMemoryKey- return- }- stableFrames = target === saved- && Math.abs(element.scrollTop - target) <= 1- && dimensionsStable- ? stableFrames + 1- : 0- // Draft hydration can resize the mobile composer one or two frames- // after the list first reaches its saved offset. Wait through that- // delayed viewport measurement so its normal resize compensation- // cannot become the final restored position.- if (stableFrames < 4 && attempts < 120) {- restoreUntilSettled()- } else {- restoredScrollKeyRef.current = scrollMemoryKey- }- })- }- restoreUntilSettled()- return () => {- window.cancelAnimationFrame(frame)- }- }, [- heroMeasured,- isLoading,- rememberedScrollTop,- scrollAnchorReady,- scrollMemoryKey,- scrollRef,- scrollToMessageId,- virtualizer,- ])- useLayoutEffect(() => {- const element = scrollRef.current- if (!element || !scrollMemoryKey) return- return registerActiveMessageScrollCapture(scrollMemoryKey, element)- }, [scrollMemoryKey, scrollRef])-useLayoutEffect(() => {const element = scrollRef.currentif (!element || !selectMode || selectedIds.size === 0) returndiff --git a/src/web/src/components/community/messages/message-list-types.ts b/src/web/src/components/community/messages/message-list-types.tsindex 5985543e4..c4bcde5bc 100644--- a/src/web/src/components/community/messages/message-list-types.ts+++ b/src/web/src/components/community/messages/message-list-types.ts@@ -4,7 +4,6 @@ import type { OpenProfile } from "@/components/community/social/profile-types"export type MessageListProps = {channel: string- scrollMemoryKey?: stringmessages: Msg[]loading?: booleanpinnedIds?: Set<string>diff --git a/src/web/src/components/community/messages/message-scroll-memory.test.ts b/src/web/src/components/community/messages/message-scroll-memory.test.tsdeleted file mode 100644index 6e0eb7a5d..000000000--- a/src/web/src/components/community/messages/message-scroll-memory.test.ts+++ /dev/null@@ -1,49 +0,0 @@-import { beforeEach, describe, expect, it } from "vitest"-import {- captureActiveMessageScrollPosition,- clearMessageScrollPositions,- readMessageScrollPosition,- registerActiveMessageScrollCapture,- writeMessageScrollPosition,-} from "./message-scroll-memory"--describe("message scroll memory", () => {- beforeEach(clearMessageScrollPositions)-- it("keeps the latest non-negative position for a surface", () => {- writeMessageScrollPosition("channel:a", 220)- writeMessageScrollPosition("channel:a", 180)- writeMessageScrollPosition("channel:b", -10)- expect(readMessageScrollPosition("channel:a")).toBe(180)- expect(readMessageScrollPosition("channel:b")).toBe(0)- })-- it("bounds old surface positions", () => {- for (let index = 0; index < 51; index += 1) {- writeMessageScrollPosition(`channel:${index}`, index)- }- expect(readMessageScrollPosition("channel:0")).toBeUndefined()- expect(readMessageScrollPosition("channel:50")).toBe(50)- })-- it("captures every connected visible scroller and unregisters exactly", () => {- const connected = { isConnected: true, clientHeight: 692, scrollTop: 2200 } as HTMLElement- const hidden = { isConnected: true, clientHeight: 0, scrollTop: 900 } as HTMLElement- const detached = { isConnected: false, clientHeight: 692, scrollTop: 700 } as HTMLElement- const unregisterConnected = registerActiveMessageScrollCapture("channel:a", connected)- const unregisterHidden = registerActiveMessageScrollCapture("channel:hidden", hidden)- const unregisterDetached = registerActiveMessageScrollCapture("channel:detached", detached)-- captureActiveMessageScrollPosition()- expect(readMessageScrollPosition("channel:a")).toBe(2200)- expect(readMessageScrollPosition("channel:hidden")).toBeUndefined()- expect(readMessageScrollPosition("channel:detached")).toBeUndefined()-- unregisterConnected()- unregisterHidden()- unregisterDetached()- connected.scrollTop = 1400- captureActiveMessageScrollPosition()- expect(readMessageScrollPosition("channel:a")).toBe(2200)- })-})diff --git a/src/web/src/components/community/messages/message-scroll-memory.ts b/src/web/src/components/community/messages/message-scroll-memory.tsdeleted file mode 100644index 2e9407537..000000000--- a/src/web/src/components/community/messages/message-scroll-memory.ts+++ /dev/null@@ -1,38 +0,0 @@-const MAX_REMEMBERED_MESSAGE_SCROLLS = 50-const positions = new Map<string, number>()-const activeCaptures = new Map<symbol, () => void>()--export function readMessageScrollPosition(key: string): number | undefined {- return positions.get(key)-}--export function writeMessageScrollPosition(key: string, scrollTop: number): void {- positions.delete(key)- positions.set(key, Math.max(0, scrollTop))- while (positions.size > MAX_REMEMBERED_MESSAGE_SCROLLS) {- const oldest = positions.keys().next().value- if (oldest === undefined) break- positions.delete(oldest)- }-}--export function clearMessageScrollPositions(): void {- positions.clear()-}--export function registerActiveMessageScrollCapture(- key: string,- element: HTMLElement,-): () => void {- const token = Symbol(key)- activeCaptures.set(token, () => {- if (element.isConnected && element.clientHeight > 0) {- writeMessageScrollPosition(key, element.scrollTop)- }- })- return () => activeCaptures.delete(token)-}--export function captureActiveMessageScrollPosition(): void {- activeCaptures.forEach((capture) => capture())-}diff --git a/src/web/src/components/community/shell/use-community-navigation-controller.test.ts b/src/web/src/components/community/shell/use-community-navigation-controller.test.tsindex ad2f106f9..1e553e48d 100644--- a/src/web/src/components/community/shell/use-community-navigation-controller.test.ts+++ b/src/web/src/components/community/shell/use-community-navigation-controller.test.ts@@ -10,7 +10,6 @@ const mocks = vi.hoisted(() => ({push: vi.fn(),replace: vi.fn(),prefetch: vi.fn(),- captureScroll: vi.fn(),frame: {current: null as CommunityCommittedFrame | null,},@@ -25,10 +24,6 @@ vi.mock("next/navigation", () => ({prefetch: mocks.prefetch,}),}))-vi.mock("@/components/community/messages/message-scroll-memory", () => ({- captureActiveMessageScrollPosition: mocks.captureScroll,-}))-type Result = ReturnType<typeof useCommunityNavigationController>function Capture({ onResult }: { onResult: (result: Result) => void }) {@@ -61,7 +56,6 @@ describe("useCommunityNavigationController", () => {mocks.push.mockReset()mocks.replace.mockReset()mocks.prefetch.mockReset()- mocks.captureScroll.mockReset()mocks.frame.current = { ...normalizeCommunityHref("/c/me"), revision: 0 }const windowTarget = new EventTarget() as EventTarget & { navigation: EventTarget }windowTarget.navigation = new EventTarget()@@ -163,34 +157,6 @@ describe("useCommunityNavigationController", () => {expect(mocks.push).toHaveBeenCalledTimes(1)})- it("captures scroll before imperative and browser-history navigation", async () => {- const hook = await renderController()- await act(async () => hook.current.push("/c/me/friends"))- expect(mocks.captureScroll).toHaveBeenCalledTimes(1)-- await act(async () => (- window as unknown as { navigation: EventTarget }- ).navigation.dispatchEvent(new Event("navigate")))- expect(mocks.captureScroll).toHaveBeenCalledTimes(2)-- await act(async () => window.dispatchEvent(new Event("popstate")))- expect(mocks.captureScroll).toHaveBeenCalledTimes(2)- await hook.unmount()- ;(window as unknown as { navigation: EventTarget }).navigation.dispatchEvent(new Event("navigate"))- expect(mocks.captureScroll).toHaveBeenCalledTimes(2)- })-- it("captures browser history through popstate when the Navigation API is unavailable", async () => {- delete (window as unknown as { navigation?: EventTarget }).navigation- const hook = await renderController()-- await act(async () => window.dispatchEvent(new Event("popstate")))- expect(mocks.captureScroll).toHaveBeenCalledOnce()- await hook.unmount()- window.dispatchEvent(new Event("popstate"))- expect(mocks.captureScroll).toHaveBeenCalledOnce()- })-it("commits only the latest async destination", async () => {const hook = await renderController()let resolveFirst!: (href: string) => voiddiff --git a/src/web/src/components/community/shell/use-community-navigation-controller.ts b/src/web/src/components/community/shell/use-community-navigation-controller.tsindex 1763f4f7f..03253ef28 100644--- a/src/web/src/components/community/shell/use-community-navigation-controller.ts+++ b/src/web/src/components/community/shell/use-community-navigation-controller.ts@@ -14,7 +14,6 @@ import {type CommunityCommittedFrame,} from "@/lib/community/community-route"import type { ShellRouter } from "./shell-frame-types"-import { captureActiveMessageScrollPosition } from "@/components/community/messages/message-scroll-memory"export type CommunityNavigationController = {publishedHref: string@@ -65,27 +64,15 @@ export function useCommunityNavigationController(useEffect(() => {if (typeof window === "undefined") return- const navigationApi = (window as Window & { navigation?: EventTarget }).navigation- const onNavigate = () => captureActiveMessageScrollPosition()- const onPopStateCapture = () => captureActiveMessageScrollPosition()const onPopState = () => cancelPendingNavigation()- navigationApi?.addEventListener("navigate", onNavigate)- if (!navigationApi) {- window.addEventListener("popstate", onPopStateCapture, { capture: true })- }window.addEventListener("popstate", onPopState)return () => {- navigationApi?.removeEventListener("navigate", onNavigate)- if (!navigationApi) {- window.removeEventListener("popstate", onPopStateCapture, { capture: true })- }window.removeEventListener("popstate", onPopState)}}, [cancelPendingNavigation])const push = useCallback((href: string) => {if (href === publishedHref) return- captureActiveMessageScrollPosition()supersedeNavigationIntent(gateRef.current)pendingBaselineRevisionRef.current = committedFrame.revisionpendingBaselineLeafRef.current = committedFrame.leafKey@@ -96,7 +83,6 @@ export function useCommunityNavigationController(const replace = useCallback((href: string) => {if (href === publishedHref) return- captureActiveMessageScrollPosition()supersedeNavigationIntent(gateRef.current)pendingBaselineRevisionRef.current = committedFrame.revisionpendingBaselineLeafRef.current = committedFrame.leafKey@@ -117,7 +103,6 @@ export function useCommunityNavigationController(setPendingHref(null)return}- captureActiveMessageScrollPosition()setPendingHref(href)router.push(href)})diff --git a/src/web/src/hooks/community/use-channel-message-feed.test.ts b/src/web/src/hooks/community/use-channel-message-feed.test.tsindex 026bba790..3cb5775ef 100644--- a/src/web/src/hooks/community/use-channel-message-feed.test.ts+++ b/src/web/src/hooks/community/use-channel-message-feed.test.ts@@ -5,12 +5,16 @@ import { useChannelMessageFeed } from "./use-channel-message-feed"const mocks = vi.hoisted(() => ({readState: {- snapshot: { lastReadMessageId: null as string | null, lastReadSeq: 2 },+ snapshot: {+ lastReadMessageId: "authoritative-anchor" as string | null,+ lastReadSeq: 2,+ } as { lastReadMessageId: string | null; lastReadSeq: number } | null,isFetching: false,},messages: {messages: [{ id: "self", authorId: "viewer" },+ { id: "authoritative-anchor", authorId: "viewer" },{ id: "peer", authorId: "peer" },],anchorReconciled: true,@@ -41,22 +45,7 @@ vi.mock("./use-channel-panels", () => ({usePins: () => ({ pins: [], isLoading: false }),}))-function Capture({ preferCachedWindowOnMount = false }: { preferCachedWindowOnMount?: boolean }) {- const result = useChannelMessageFeed({- channelId: "channel",- serverId: "server",- viewerUserId: "viewer",- isChildChannel: false,- anchorMessageId: null,- preferCachedWindowOnMount,- })- return createElement("output", {- "data-divider": result.newDividerBefore,- "data-unread": result.unreadCount,- })-}--function CaptureDefaultMount() {+function Capture() {const result = useChannelMessageFeed({channelId: "channel",serverId: "server",@@ -72,16 +61,23 @@ function CaptureDefaultMount() {describe("useChannelMessageFeed", () => {beforeEach(() => {+ mocks.readState.snapshot = {+ lastReadMessageId: "authoritative-anchor",+ lastReadSeq: 2,+ }+ mocks.readState.isFetching = falsemocks.useMessages.mockReset()mocks.watermark.mockReset()})- it("revalidates a normal mount and preserves the cached window on a restored mount", () => {+ it("always revalidates a mount and reconciles the authoritative server anchor", () => {let renderer: TestRenderer.ReactTestRendereract(() => {- renderer = TestRenderer.create(createElement(CaptureDefaultMount))+ renderer = TestRenderer.create(createElement(Capture))})expect(mocks.useMessages).toHaveBeenLastCalledWith("channel", expect.objectContaining({+ lastReadMessageId: "authoritative-anchor",+ waitForAnchor: true,reconcileLateAnchor: true,revalidateOnMount: true,}))@@ -89,13 +85,32 @@ describe("useChannelMessageFeed", () => {"data-divider": "peer","data-unread": 3,})+ act(() => renderer!.unmount())+ })+ it("gates the messages request until the mount-owned server anchor resolves", () => {+ mocks.readState.snapshot = null+ mocks.readState.isFetching = true+ let renderer: TestRenderer.ReactTestRendereract(() => {- renderer!.update(createElement(Capture, { preferCachedWindowOnMount: true }))+ renderer = TestRenderer.create(createElement(Capture))})expect(mocks.useMessages).toHaveBeenLastCalledWith("channel", expect.objectContaining({- reconcileLateAnchor: false,- revalidateOnMount: false,+ lastReadMessageId: undefined,+ waitForAnchor: true,+ reconcileLateAnchor: true,+ revalidateOnMount: true,+ }))++ mocks.readState.snapshot = {+ lastReadMessageId: "resolved-anchor",+ lastReadSeq: 7,+ }+ mocks.readState.isFetching = false+ act(() => renderer!.update(createElement(Capture)))+ expect(mocks.useMessages).toHaveBeenLastCalledWith("channel", expect.objectContaining({+ lastReadMessageId: "resolved-anchor",+ waitForAnchor: true,}))act(() => renderer!.unmount())})diff --git a/src/web/src/hooks/community/use-channel-message-feed.ts b/src/web/src/hooks/community/use-channel-message-feed.tsindex 2d1aaf2d0..5182b67b5 100644--- a/src/web/src/hooks/community/use-channel-message-feed.ts+++ b/src/web/src/hooks/community/use-channel-message-feed.ts@@ -12,14 +12,12 @@ export function useChannelMessageFeed({viewerUserId,isChildChannel: _isChildChannel,anchorMessageId,- preferCachedWindowOnMount = false,}: {channelId: string | nullserverId: stringviewerUserId: stringisChildChannel: booleananchorMessageId: string | null- preferCachedWindowOnMount?: boolean}) {const readState = useChannelReadStateSnapshot(channelId)const readSnapshot = readState.snapshot@@ -29,9 +27,9 @@ export function useChannelMessageFeed({? undefined: (readSnapshot?.lastReadMessageId ?? null),anchorMessageId,- waitForAnchor: false,- reconcileLateAnchor: !preferCachedWindowOnMount,- revalidateOnMount: !preferCachedWindowOnMount,+ waitForAnchor: true,+ reconcileLateAnchor: true,+ revalidateOnMount: true,})const { newDividerBefore, anchorFound } = useMemo(() => {if (!readSnapshot) return { newDividerBefore: undefined, anchorFound: false }diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.tsindex 76075f4b8..10dd6d73a 100644--- a/src/web/src/hooks/community/use-scroll-anchor.ts+++ b/src/web/src/hooks/community/use-scroll-anchor.ts@@ -395,7 +395,6 @@ export function useScrollAnchor({viewerUserId,heroHeight,heroMeasured,- restoredScrollTop,}: {items: FlatItem[]newDividerBefore?: string@@ -415,7 +414,6 @@ export function useScrollAnchor({// `DecideScrollActionInput.heroMeasured`'s doc comment for the bug this// prevents (mount firing on a stale, default-0 `scrollMargin`).heroMeasured: boolean- restoredScrollTop?: number}): {scrollRef: React.RefObject<HTMLDivElement | null>virtualizer: ReactVirtualizer<HTMLDivElement, Element>@@ -428,8 +426,8 @@ export function useScrollAnchor({const stateRef = useRef<ScrollAnchorState>(createScrollAnchorState())const messages = extractScrollAnchorMessages(items)const tailId = messages[messages.length - 1]?.id ?? null- const wasAtEndRef = useRef(restoredScrollTop === undefined)- const userScrolledAwayRef = useRef(restoredScrollTop !== undefined)+ const wasAtEndRef = useRef(true)+ const userScrolledAwayRef = useRef(false)const measuredRowHeightsRef = useRef(new WeakMap<Element, number>())const bottomRepinQueuedRef = useRef(false)@@ -593,7 +591,6 @@ export function useScrollAnchor({switch (action.type) {case "mount": {- if (restoredScrollTop !== undefined) returnconst idx = action.newDividerBefore ? findMountScrollTargetIndex(items, action.newDividerBefore) : nullif (idx !== null) {virtualizer.scrollToIndex(idx, { align: "center" })@@ -612,7 +609,7 @@ export function useScrollAnchor({// derives from items) — `items` alone is the correct dep, not a// secondary `messages` dep, avoiding a re-derivation-triggered re-fire.// eslint-disable-next-line react-hooks/exhaustive-deps- }, [items, newDividerBefore, initialScrollReady, heroMeasured, hasMoreNewer, viewerUserId, virtualizer, restoredScrollTop])+ }, [items, newDividerBefore, initialScrollReady, heroMeasured, hasMoreNewer, viewerUserId, virtualizer])const consumedPresentVersionRef = useRef(0)useLayoutEffect(() => {diff --git a/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts b/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.tsindex 384c2da29..d1e62a8a8 100644--- a/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts+++ b/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts@@ -175,10 +175,6 @@ test.describe.serial("forum sidebar Stage B request shape", () => {const initialCombined = page.waitForResponse((response) =>response.ok() && isSidebarRequest(response.url(), serverId),)- const initialNewest = page.waitForResponse((response) => {- if (!response.ok() || !isChannelMessagesRequest(response.url(), threadId)) return false- return !new URL(response.url()).searchParams.has("anchor")- })const initialAnchored = page.waitForResponse((response) => {if (!response.ok() || !isChannelMessagesRequest(response.url(), threadId)) return falsereturn new URL(response.url()).searchParams.has("anchor")@@ -194,7 +190,7 @@ test.describe.serial("forum sidebar Stage B request shape", () => {} finally {releaseFirstAnchor()}- await Promise.all([initialCombined, initialNewest, initialAnchored])+ await Promise.all([initialCombined, initialAnchored])await expect.poll(() => new URL(page.url()).pathname).toBe(`/c/channels/${serverId}/${threadId}`,)@@ -214,9 +210,9 @@ test.describe.serial("forum sidebar Stage B request shape", () => {const coldSuccessfulMessageResponses = successfulResponses.filter((url) =>isChannelMessagesRequest(url, threadId),)- expect(coldSuccessfulMessageResponses).toHaveLength(2)+ expect(coldSuccessfulMessageResponses).toHaveLength(1)expect(coldSuccessfulMessageResponses.filter((url) => !new URL(url).searchParams.has("anchor")))- .toHaveLength(1)+ .toHaveLength(0)expect(coldSuccessfulMessageResponses.filter((url) => new URL(url).searchParams.has("anchor"))).toHaveLength(1)expect(anchorRouteRequests).toBe(1)@@ -253,8 +249,8 @@ test.describe.serial("forum sidebar Stage B request shape", () => {const refreshAnchorResponses = refreshSuccessfulMessageResponses.filter((url) =>new URL(url).searchParams.has("anchor"),)- expect(refreshNewestResponses.length).toBeLessThanOrEqual(1)- expect(refreshAnchorResponses.length).toBeLessThanOrEqual(1)+ expect(refreshNewestResponses).toHaveLength(0)+ expect(refreshAnchorResponses).toHaveLength(1)expect(new Set(refreshSuccessfulMessageResponses).size).toBe(refreshSuccessfulMessageResponses.length)})diff --git a/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts b/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.tsindex 0800bc89d..3879279d5 100644--- a/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts+++ b/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts@@ -257,7 +257,7 @@ test("My Bots renders seven-day usage and replace-all quota across responsive thawait page.waitForTimeout(300)await attachScreenshot(page, testInfo, "my-bots-telemetry-pc-dark")- await page.setViewportSize({ width: 390, height: 844 })+ await page.setViewportSize({ width: 639, height: 844 })await page.emulateMedia({ colorScheme: "light" })await expect.poll(() => page.evaluate(() => document.documentElement.classList.contains("dark"))).toBe(false)await page.waitForTimeout(300)@@ -269,6 +269,28 @@ test("My Bots renders seven-day usage and replace-all quota across responsive thexpect(mobileUsageBox?.height).toBeGreaterThanOrEqual(44)expect(mobileUsageBox?.width).toBeGreaterThanOrEqual(44)await mobileUsageTrigger.tap()+ const mobileUsageDetail = page.locator('[data-slot="popover-content"]:visible')+ await expect.poll(async () => (await mobileUsageDetail.boundingBox())?.height ?? 0)+ .toBeLessThanOrEqual(260)+ const mobileDayTargets = page.locator(+ `[data-testid^="${tid.botUsageDay("bot_codex", "")}"]:visible`,+ )+ await expect(mobileDayTargets).toHaveCount(7)+ await expect.poll(async () => {+ const boxes = await mobileDayTargets.evaluateAll((elements) => elements.map((element) => {+ const box = element.getBoundingClientRect()+ return { width: box.width, height: box.height }+ }))+ return boxes.every((box) => box.width >= 44 && box.height >= 44)+ }).toBe(true)+ const mobileDayBoxes = await mobileDayTargets.evaluateAll((elements) => elements.map((element) => {+ const box = element.getBoundingClientRect()+ return { width: box.width, height: box.height, y: Math.round(box.y) }+ }))+ expect(new Set(mobileDayBoxes.map((box) => box.y)).size).toBeLessThanOrEqual(2)+ await expect(page.locator(+ `[data-testid^="${tid.botUsageDay("bot_codex", "")}"][aria-pressed="true"]:visible`,+ )).toHaveCount(1)const mobileUsageDay = page.locator(`[data-testid="${tid.botUsageDay("bot_codex", "2026-08-26")}"]:visible`,)@@ -277,7 +299,7 @@ test("My Bots renders seven-day usage and replace-all quota across responsive thawait expect.poll(async () => (await mobileUsageDay.boundingBox())?.width ?? 0).toBeGreaterThanOrEqual(44)await mobileUsageDay.tap()- const mobileUsageDetail = page.locator('[data-slot="popover-content"]:visible')+ await expect(mobileUsageDay).toHaveAttribute("aria-pressed", "true")await expect(mobileUsageDetail).toContainText("Input700")await expect(mobileUsageDetail).toContainText("Output300")await expect(mobileUsageDetail).toContainText("CacheUnavailable")@@ -293,4 +315,14 @@ test("My Bots renders seven-day usage and replace-all quota across responsive thawait page.waitForTimeout(300)await expectNoHorizontalOverflow(page)await attachScreenshot(page, testInfo, "my-bots-telemetry-mobile-dark")++ await page.setViewportSize({ width: 640, height: 844 })+ await expect(mobileUsageTrigger).toBeHidden()+ await expect(page.locator(+ `[data-testid^="${tid.botUsageDay("bot_codex", "")}"]:visible`,+ )).toHaveCount(7)+ await expect.poll(async () => (await usage.boundingBox())?.height ?? 0).toBe(42)+ const desktopBoundaryDay = page.getByTestId(tid.botUsageDay("bot_codex", "2026-08-26"))+ await desktopBoundaryDay.hover()+ await expect(page.locator('[data-slot="tooltip-content"]:visible')).toContainText("Input700")})diff --git a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.tsindex a54d4491a..8c2034621 100644--- a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts+++ b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts@@ -1,4 +1,4 @@-import type { Locator, Page } from "@playwright/test"+import type { Locator, Page, Request } from "@playwright/test"import { test, expect, userId } from "./_fixtures/community-fixture"import {composerEditable,@@ -158,6 +158,130 @@ async function latestSeq(page: Page, channelId: string): Promise<number> {return ((await response.json()) as { latestSeq: number }).latestSeq}+type ReadState = {+ lastReadMessageId: string | null+ lastReadSeq: number+}++async function settledReadState(page: Page, channelId: string): Promise<ReadState> {+ let previous: ReadState | null = null+ for (let attempt = 0; attempt < 30; attempt += 1) {+ const response = await page.request.get(`/api/community/channels/${channelId}/read-state`)+ expect(response.ok()).toBe(true)+ const current = await response.json() as ReadState+ if (+ current.lastReadMessageId+ && previous?.lastReadMessageId === current.lastReadMessageId+ && previous.lastReadSeq === current.lastReadSeq+ ) {+ return current+ }+ previous = current+ await page.waitForTimeout(100)+ }+ throw new Error(`read state did not settle for ${channelId}: ${JSON.stringify(previous)}`)+}++type SurfaceGetTracker = {+ abortedMessageGets: number+ abortedReadStateGets: number+ failures: string[]+ messageUrls: string[]+ readStateUrls: string[]+ inFlight: () => number+ stop: () => void+}++function trackSurfaceGets(page: Page, channelId: string): SurfaceGetTracker {+ const observedRequests = new Set<Request>()+ const kind = (request: Request): "messages" | "read-state" | null => {+ if (request.method() !== "GET") return null+ const pathname = new URL(request.url()).pathname+ if (pathname === `/api/community/channels/${channelId}/messages`) return "messages"+ if (pathname === `/api/community/channels/${channelId}/read-state`) return "read-state"+ return null+ }+ const onRequest = (request: Request) => {+ if (kind(request)) observedRequests.add(request)+ }+ const tracker: SurfaceGetTracker = {+ abortedMessageGets: 0,+ abortedReadStateGets: 0,+ failures: [],+ messageUrls: [],+ readStateUrls: [],+ inFlight: () => observedRequests.size,+ stop: () => {+ page.off("request", onRequest)+ page.off("requestfinished", onFinished)+ page.off("requestfailed", onFailed)+ },+ }+ const onFinished = (request: Request) => {+ if (!observedRequests.delete(request)) return+ const requestKind = kind(request)+ if (requestKind === "messages") tracker.messageUrls.push(request.url())+ if (requestKind === "read-state") tracker.readStateUrls.push(request.url())+ }+ const onFailed = (request: Request) => {+ if (!observedRequests.delete(request)) return+ const requestKind = kind(request)+ if (!requestKind) return+ const error = request.failure()?.errorText ?? "unknown request failure"+ if (!error.includes("ERR_ABORTED")) {+ tracker.failures.push(`${requestKind}: ${error}`)+ return+ }+ if (requestKind === "messages") tracker.abortedMessageGets += 1+ else tracker.abortedReadStateGets += 1+ }+ page.on("request", onRequest)+ page.on("requestfinished", onFinished)+ page.on("requestfailed", onFailed)+ return tracker+}++async function expectRetainedMountGets(+ page: Page,+ channelId: string,+ departureReadState: ReadState,+ tracker: SurfaceGetTracker,+) {+ await expect.poll(() => tracker.readStateUrls.length).toBe(1)+ await page.waitForTimeout(300)+ await expect.poll(() => tracker.inFlight()).toBe(0)+ const settledMessageCount = tracker.messageUrls.length+ await page.waitForTimeout(300)+ expect(tracker.inFlight()).toBe(0)+ expect(tracker.messageUrls).toHaveLength(settledMessageCount)++ expect(tracker.messageUrls.length).toBeGreaterThanOrEqual(1)+ expect(tracker.messageUrls.length).toBeLessThanOrEqual(2)+ const anchors = tracker.messageUrls.map((url) => new URL(url).searchParams.get("anchor"))+ expect(anchors[0]).toBe(departureReadState.lastReadMessageId)+ const counts = new Map<string, number>()+ for (const anchor of anchors) {+ const identity = anchor ?? "<newest>"+ counts.set(identity, (counts.get(identity) ?? 0) + 1)+ }+ for (const count of counts.values()) expect(count).toBe(1)++ if (anchors.length === 2) {+ const newerAnchor = anchors[1]+ expect(newerAnchor).not.toBeNull()+ expect(newerAnchor).not.toBe(anchors[0])+ await expect(page.getByTestId(tid.message(newerAnchor!))).toBeVisible()+ const advancedReadState = await settledReadState(page, channelId)+ expect(advancedReadState.lastReadSeq).toBeGreaterThan(departureReadState.lastReadSeq)+ expect(newerAnchor).toBe(advancedReadState.lastReadMessageId)+ }++ expect(tracker.readStateUrls).toHaveLength(1)+ expect(tracker.abortedReadStateGets).toBeLessThanOrEqual(1)+ expect(tracker.abortedMessageGets).toBeLessThanOrEqual(1)+ expect(tracker.failures).toEqual([])+}+test("mobile reply, avatar mention, and typing space keep exact backend and WS identity", async ({ asUser }) => {test.setTimeout(240_000)const stamp = Date.now()@@ -175,6 +299,13 @@ test("mobile reply, avatar mention, and typing space keep exact backend and WS iconst threadId = await seedThread("alice", openerId, `mobile-thread-${stamp}`)const threadBobMessageId = await seedMessage("bob", threadId, `thread **target** ${stamp}`)const dmId = await seedDm("alice", userId("bob"))+ for (let index = 0; index < 24; index += 1) {+ await seedMessage(index % 2 === 0 ? "alice" : "bob", dmId, `dm scroll row ${index} ${stamp}`)+ }+ await seedMessage("bob", dmId, Array.from(+ { length: 70 },+ (_, index) => `dm scroll line ${index} ${stamp}`,+ ).join("\n\n"))const bobInfo = await memberInfo("alice", serverId, userId("bob"))const aliceInfo = await memberInfo("alice", serverId, userId("alice"))@@ -484,7 +615,27 @@ test("mobile reply, avatar mention, and typing space keep exact backend and WS iexpect(spaceAfter?.y).toBeCloseTo(spaceBefore!.y, 0)expect(await latestSeq(alice.page, channelId)).toBe(beforeTypingSeq)- await alice.page.goto(`/c/me/${dmId}`, { waitUntil: "commit" })+ const dmSeqBeforeDirect = await latestSeq(alice.page, dmId)+ const directDmBody = `profile direct dm ${stamp}`+ await finalChannelMessage.getByRole("button", {+ name: `Open ${bobInfo.name} profile; long press to mention`,+ }).click()+ const directProfileCard = alice.page.getByTestId(tid.profileCard)+ await expect(directProfileCard).toBeVisible()+ await directProfileCard.getByPlaceholder(`Message @${bobInfo.name}`).fill(directDmBody)+ const directResponsePromise = alice.page.waitForResponse((response) => (+ response.request().method() === "POST"+ && new URL(response.url()).pathname === `/api/community/channels/${dmId}/messages`+ ))+ await directProfileCard.getByRole("button", { name: "Send message" }).click()+ const directResponse = await directResponsePromise+ expect(directResponse.status()).toBe(201)+ const directPayload = await directResponse.json() as { message: { id: string } }+ await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/me/${dmId}`)+ expect(await latestSeq(alice.page, dmId)).toBe(dmSeqBeforeDirect + 1)+ await expect.poll(() => bobProxy.frames.filter((frame) => (+ frameHasMessage(frame, dmId, directPayload.message.id)+ )).length).toBe(1)await bob.page.goto(`/c/me/${dmId}`, { waitUntil: "commit" })await ignoreNextDevToolsPointerCapture(alice.page)await ignoreNextDevToolsPointerCapture(bob.page)@@ -545,6 +696,46 @@ test("mobile reply, avatar mention, and typing space keep exact backend and WS iexpect((await dmTypingSpace.boundingBox())?.height).toBe(0)expect(await latestSeq(alice.page, dmId)).toBe(beforeDmTypingSeq)+ const dmScroller = alice.page.getByTestId(tid.messageScroller)+ await expect.poll(() => dmScroller.evaluate((element) => (+ element.scrollHeight - element.clientHeight+ ))).toBeGreaterThan(1600)+ const departedDmScrollTop = await dmScroller.evaluate((element) => {+ element.scrollTop = 900+ element.dispatchEvent(new Event("scroll"))+ return element.scrollTop+ })+ expect(departedDmScrollTop).toBe(900)+ const dmReadState = await settledReadState(alice.page, dmId)+ const dmReturnGets = trackSurfaceGets(alice.page, dmId)+ await alice.page.getByRole("button", { name: "Back" }).click()+ await expect.poll(() => new URL(alice.page.url()).pathname).toBe("/c/me")+ await alice.page.getByTestId(tid.dmRow(dmId)).click()+ await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/me/${dmId}`)+ await expect(alice.page.getByTestId(tid.message(dmReadState.lastReadMessageId!))).toBeVisible()+ await expectRetainedMountGets(alice.page, dmId, dmReadState, dmReturnGets)+ expect(Math.abs(await dmScroller.evaluate((element) => element.scrollTop) - departedDmScrollTop))+ .toBeGreaterThan(50)+ dmReturnGets.stop()++ const departedDmReloadScrollTop = await dmScroller.evaluate((element) => {+ element.scrollTop = 700+ element.dispatchEvent(new Event("scroll"))+ return element.scrollTop+ })+ expect(departedDmReloadScrollTop).toBe(700)+ const dmReloadReadState = await settledReadState(alice.page, dmId)+ const dmReloadGets = trackSurfaceGets(alice.page, dmId)+ await alice.page.reload({ waitUntil: "commit" })+ await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/me/${dmId}`)+ await expect(alice.page.getByTestId(tid.message(dmReloadReadState.lastReadMessageId!))).toBeVisible()+ await expectRetainedMountGets(alice.page, dmId, dmReloadReadState, dmReloadGets)+ expect(Math.abs(+ await dmScroller.evaluate((element) => element.scrollTop) - departedDmReloadScrollTop,+ )).toBeGreaterThan(50)+ expect(await latestSeq(alice.page, dmId)).toBe(beforeDmTypingSeq)+ dmReloadGets.stop()+await alice.page.emulateMedia({ reducedMotion: "reduce" })await alice.page.evaluate(() => {const original = Element.prototype.animate@@ -575,23 +766,12 @@ test("mobile reply, avatar mention, and typing space keep exact backend and WS iawait navigationEditable.fill(navigationDraft)const readingPosition = await scroller.evaluate((element) => {element.scrollTop = Math.min(2200, Math.max(0, element.scrollHeight - element.clientHeight))+ element.dispatchEvent(new Event("scroll"))return element.scrollTop})expect(readingPosition).toBe(2200)- const getObservationStartedAt = Date.now()- const channelMessageGets: Array<{ route: string; sinceMs: number; url: string }> = []- alice.page.on("request", (request) => {- if (- request.method() === "GET"- && new URL(request.url()).pathname === `/api/community/channels/${channelId}/messages`- ) {- channelMessageGets.push({- route: new URL(request.frame().url()).pathname,- sinceMs: Date.now() - getObservationStartedAt,- url: request.url(),- })- }- })+ const channelReadState = await settledReadState(alice.page, channelId)+ const channelReturnGets = trackSurfaceGets(alice.page, channelId)await alice.page.getByRole("button", { name: `Go to server ${serverName}` }).click()await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/channels/${serverId}`)await alice.page.getByTestId(tid.channelRow(channelId)).evaluate((element) => (@@ -599,15 +779,14 @@ test("mobile reply, avatar mention, and typing space keep exact backend and WS i))await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/channels/${serverId}/${channelId}`)await expect(composerEditable(alice.page)).toContainText(navigationDraft)- await alice.page.waitForTimeout(1600)- expect(await scroller.evaluate((element) => element.scrollTop)).toBeCloseTo(readingPosition, 0)- expect(- channelMessageGets.length,- `channel message GETs after list return: ${JSON.stringify(channelMessageGets)}`,- ).toBeLessThanOrEqual(1)+ await expect(alice.page.getByTestId(tid.message(channelReadState.lastReadMessageId!))).toBeVisible()+ expect(Math.abs(await scroller.evaluate((element) => element.scrollTop) - readingPosition))+ .toBeGreaterThan(50)+ await expectRetainedMountGets(alice.page, channelId, channelReadState, channelReturnGets)+ channelReturnGets.stop()})-test("mobile channel scroll restoration remains stable after navigation settles", async ({ asUser }) => {+test("mobile thread return uses server read state instead of tab-local pixel memory", async ({ asUser }) => {const stamp = Date.now()const serverName = `Mobile-scroll-${stamp}`const serverId = await seedServer("alice", serverName)@@ -621,11 +800,19 @@ test("mobile channel scroll restoration remains stable after navigation settles").join("\n\n"))const openerId = await seedMessage("alice", channelId, `scroll thread opener ${stamp}`)const threadId = await seedThread("alice", openerId, `scroll-thread-${stamp}`)+ for (let index = 0; index < 24; index += 1) {+ await seedMessage("alice", threadId, `thread scroll row ${index} ${stamp}`)+ }+ await seedMessage("alice", threadId, Array.from(+ { length: 70 },+ (_, index) => `thread scroll line ${index} ${stamp}`,+ ).join("\n\n"))const threadReplyId = await seedMessage("alice", threadId, `scroll thread reply ${stamp}`)const alice = await asUser("alice")await alice.page.setViewportSize({ width: 390, height: 844 })await alice.page.goto(`/c/channels/${serverId}/${channelId}`, { waitUntil: "commit" })+ await alice.page.waitForLoadState("domcontentloaded")await ignoreNextDevToolsPointerCapture(alice.page)const editable = composerEditable(alice.page)const scroller = alice.page.getByTestId(tid.messageScroller)@@ -636,38 +823,31 @@ test("mobile channel scroll restoration remains stable after navigation settles"const draft = `stable navigation draft ${stamp}`await editable.fill(draft)- expect(await scroller.evaluate((element) => {- element.scrollTop = 2200- return element.scrollTop- })).toBe(2200)-- await alice.page.getByRole("button", { name: `Go to server ${serverName}` }).click()- await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/channels/${serverId}`)- await alice.page.getByTestId(tid.channelRow(channelId)).click()- await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/channels/${serverId}/${channelId}`)- await expect(composerEditable(alice.page)).toContainText(draft)- await alice.page.waitForTimeout(1600)- expect(await scroller.evaluate((element) => element.scrollTop)).toBeCloseTo(2200, 0)-- await alice.page.getByTestId(tid.scrollToPresent).click()const threadIndicator = alice.page.getByTestId(tid.threadIndicator(openerId))await expect(threadIndicator).toBeVisible()- await alice.page.waitForTimeout(500)- await threadIndicator.focus()- await expect.poll(async () => {- const before = await scroller.evaluate((element) => element.scrollTop)- await alice.page.waitForTimeout(50)- const after = await scroller.evaluate((element) => element.scrollTop)- return after - before- }).toBe(0)- const channelBackPosition = await scroller.evaluate((element) => element.scrollTop)- expect(channelBackPosition).toBeGreaterThan(2200)await threadIndicator.click()await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/channels/${serverId}/${threadId}`)await expect(alice.page.getByTestId(tid.message(threadReplyId))).toBeVisible()+ const threadScroller = alice.page.getByTestId(tid.messageScroller)+ await expect.poll(() => threadScroller.evaluate((element) => (+ element.scrollHeight - element.clientHeight+ ))).toBeGreaterThan(1600)+ const departedThreadScrollTop = await threadScroller.evaluate((element) => {+ element.scrollTop = 900+ element.dispatchEvent(new Event("scroll"))+ return element.scrollTop+ })+ expect(departedThreadScrollTop).toBe(900)+ const threadReadState = await settledReadState(alice.page, threadId)+ const threadReturnGets = trackSurfaceGets(alice.page, threadId)await alice.page.goBack({ waitUntil: "commit" })await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/channels/${serverId}/${channelId}`)await expect(composerEditable(alice.page)).toContainText(draft)- await alice.page.waitForTimeout(1600)- expect(await scroller.evaluate((element) => element.scrollTop)).toBeCloseTo(channelBackPosition, 0)+ await alice.page.goForward({ waitUntil: "commit" })+ await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/channels/${serverId}/${threadId}`)+ await expect(alice.page.getByTestId(tid.message(threadReadState.lastReadMessageId!))).toBeVisible()+ await expectRetainedMountGets(alice.page, threadId, threadReadState, threadReturnGets)+ expect(Math.abs(await threadScroller.evaluate((element) => element.scrollTop) - departedThreadScrollTop))+ .toBeGreaterThan(50)+ threadReturnGets.stop()})diff --git a/src/web/src/test/e2e-ui/41-community-initial-load-module-skeletons.spec.ts b/src/web/src/test/e2e-ui/41-community-initial-load-module-skeletons.spec.tsindex a89278dc6..a7384c240 100644--- a/src/web/src/test/e2e-ui/41-community-initial-load-module-skeletons.spec.ts+++ b/src/web/src/test/e2e-ui/41-community-initial-load-module-skeletons.spec.ts@@ -137,6 +137,7 @@ test.describe.serial("community initial-load module skeletons", () => {let dmId: stringlet serverName: stringlet channelName: string+ let channelMessageId: stringlet privateMessage: stringtest.beforeAll(async () => {@@ -146,7 +147,7 @@ test.describe.serial("community initial-load module skeletons", () => {privateMessage = `PRIVATE COLD MESSAGE ${stamp}`serverId = await seedServer("alice", serverName)channelId = await seedChannel("alice", serverId, channelName)- await seedMessage("alice", channelId, privateMessage)+ channelMessageId = await seedMessage("alice", channelId, privateMessage)dmId = await seedDm("alice", userId("bob"))await seedDmMessage("alice", dmId, privateMessage)})@@ -252,22 +253,28 @@ test.describe.serial("community initial-load module skeletons", () => {await expect(page.getByTestId(tid.initialFrame)).toHaveCount(0, { timeout: 30_000 })await expect(page.getByTestId(tid.composerInput)).toBeVisible({ timeout: 30_000 })await expect.poll(traffic.sockets).toBe(1)- const exactMessageReads = traffic.requests.filter(({ method, pathname, search }) => (+ await expect.poll(() => traffic.responses.filter(({ method, pathname, status }) => (method === "GET"- && pathname === `/api/community/channels/${channelId}/messages`- && search === ""- ))+ && pathname === `/api/community/channels/${channelId}/read-state`+ && status === 200+ )).length).toBe(1)+ const exactMessageSearch = `?anchor=${encodeURIComponent(channelMessageId)}`await expect.poll(() => traffic.responses.filter(({ method, pathname, search, status }) => (method === "GET"&& pathname === `/api/community/channels/${channelId}/messages`- && search === ""+ && search === exactMessageSearch&& status === 200)).length).toBe(1)await page.waitForTimeout(200)+ const exactMessageReads = traffic.requests.filter(({ method, pathname, search }) => (+ method === "GET"+ && pathname === `/api/community/channels/${channelId}/messages`+ && search === exactMessageSearch+ ))const exactMessageFailures = traffic.failures.filter(({ method, pathname, search }) => (method === "GET"&& pathname === `/api/community/channels/${channelId}/messages`- && search === ""+ && search === exactMessageSearch))expect(exactMessageReads).toHaveLength(1 + exactMessageFailures.length)expect(exactMessageFailures.every(({ error }) => error === "net::ERR_ABORTED")).toBe(true)