GeezerVison is showing github.com — fix(app): contain timeline rows to cut scroll layout work by Te-River · Pull Request #54293 · anomalyco/opencode
fix(app): contain timeline rows to cut scroll layout work
#54293
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from all commits
Commits
File filter
Filter by extension
.ts
(3)
.tsx
(1)
All 2 file types selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,141 @@
import type { Locator, Page } from "@playwright/test"
import { benchmark, expect } from "../benchmark"
import { setupTimelineBenchmark } from "./session-timeline-benchmark.fixture"
import {
collectTimelineScrollMetrics,
installTimelineScrollProbe,
startTimelineScrollProbe,
} from "./session-timeline-scroll-probe"
const historyTurns = Number(process.env.SCROLL_BENCH_HISTORY_TURNS ?? 320)
const upSteps = Number(process.env.SCROLL_BENCH_UP_STEPS ?? 24)
const upDelta = Number(process.env.SCROLL_BENCH_UP_DELTA ?? -900)
const fastSteps = Number(process.env.SCROLL_BENCH_FAST_STEPS ?? 8)
const fastDelta = Number(process.env.SCROLL_BENCH_FAST_DELTA ?? 2_600)
/**
* Scroll-path pacing for a long Markdown session.
*
* The two scenarios bracket the cold tail settle: one scrolls as soon as the timeline mounts,
* the other waits until the settle finished. Metrics are reported for before/after comparison
* only; no timing or frame-rate threshold is asserted.
*/
benchmark.describe("performance: session timeline scrolling", () => {
benchmark("scrolls a long session from the cold tail", async ({ page, report }) => {
benchmark.setTimeout(300_000)
report(await runTimelineScrollBenchmark(page, { waitForColdSettle: false }))
})
benchmark("scrolls a long session after the cold tail settled", async ({ page, report }) => {
benchmark.setTimeout(300_000)
report(await runTimelineScrollBenchmark(page, { waitForColdSettle: true }))
})
})
async function runTimelineScrollBenchmark(page: Page, options: { waitForColdSettle: boolean }) {
const fixture = await setupTimelineBenchmark(page, { historyTurns, eventBatch: 1 })
// The settle removes the inline `visibility: hidden` from the virtual content once the cold
// tail finished; the second scenario starts only after that gate is gone.
if (options.waitForColdSettle)
await expect
.poll(
() =>
fixture.scroller.evaluate(
() => document.querySelector<HTMLElement>("[data-timeline-virtual-content]")?.style.visibility === "hidden",
),
{ timeout: 120_000, intervals: [100, 250, 500] },
)
.toBe(false)
const maxScroll = await fixture.scroller.evaluate((element) => element.scrollHeight - element.clientHeight)
// Calibrate before measuring: a step that never reaches the scroller would otherwise surface
// as an opaque progress timeout halfway through the run.
const calibrated = await wheelThrough(fixture.scroller, 1, upDelta)
expect(calibrated, "calibration step moves the timeline").toBeGreaterThan(0)
await installTimelineScrollProbe(page)
await startTimelineScrollProbe(page)
const upScrolled = await wheelThrough(fixture.scroller, upSteps, upDelta)
const fastScrolled = await wheelThrough(fixture.scroller, fastSteps, fastDelta)
const metrics = await collectTimelineScrollMetrics(page)
expect(metrics.frameCount).toBeGreaterThan(0)
expect(metrics.frameGapMedianMs).not.toBeNull()
expect(metrics.frameGapP95Ms).not.toBeNull()
expect(upScrolled + fastScrolled).toBeGreaterThan(0)
return {
metrics: { ...metrics, upScrolled, fastScrolled, maxScroll },
context: {
historyTurns,
upSteps,
upDelta,
fastSteps,
fastDelta,
waitedForColdSettle: options.waitForColdSettle,
...fixture.workload,
},
}
}
/**
* Steps the scroller `steps` times so the scroll stays continuous instead of stalling between round
* trips, then waits for the position to hold still. The burst ends early at either end of the
* timeline, and the net movement is returned as-is: the cold tail pin can legitimately drag the
* view back down.
*
* Assigns `scrollTop` rather than wheeling, matching the fixture's own `scrollToBottom`. The
* assignment still fires a real scroll event, so the settle path under measurement runs unchanged,
* and each step lands deterministically instead of depending on wheel delivery.
*/
async function wheelThrough(scroller: Locator, steps: number, delta: number) {
Comment thread
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more .
This retries on Execution context was destroyed because "the first scroll after load makes the app reload the same route once". If the app really reloads on the first scroll, that's a bug worth its own issue. If it's caused by how the benchmark is set up, the retry hides it and the benchmark is likely to be flaky. Either way, I don't think a benchmark should work around it silently. Can you find out what triggers the reload?
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
const start = await scroller.evaluate((element) => element.scrollTop)
for (let step = 0; step < steps; step++) {
const before = await scroller.evaluate((element) => element.scrollTop)
const max = await scroller.evaluate((element) => element.scrollHeight - element.clientHeight)
if (delta < 0 ? before <= 0 : before >= max) break
await scroller.evaluate((element, by) => {
element.scrollTop = element.scrollTop + by
}, delta)
}
await scroller.evaluate(waitForScrollToSettle, { stableFrames, settleFrameBudget })
return Math.abs((await scroller.evaluate((element) => element.scrollTop)) - start)
}
const stableFrames = 3
const settleFrameBudget = 1_200
/**
* Resolves once scrollTop repeats across consecutive frames, or once the frame budget runs out.
*
* The budget arrives as an argument: `evaluate` serializes only the function source, so a
* module-scope constant would read as `undefined` in the page and the loop would never resolve.
*/
function waitForScrollToSettle(element: HTMLElement, budget: { stableFrames: number; settleFrameBudget: number }) {
return new Promise<void>((resolve) => {
let previous = -1
let stable = 0
let frames = 0
const sample = () => {
const top = element.scrollTop
stable = top === previous ? stable + 1 : 0
previous = top
frames += 1
if (stable >= budget.stableFrames || frames >= budget.settleFrameBudget) return resolve()
requestAnimationFrame(sample)
}
requestAnimationFrame(sample)
})
}
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,130 @@
import type { Page } from "@playwright/test"
const scrollerSelector = ".scroll-view__viewport"
type TimelineScrollProbe = {
/** requestAnimationFrame timestamps collected across the measured scroll window. */
frames: number[]
longTasks: { startTime: number; duration: number }[]
scrollEvents: number
scrollTopStart: number
scrollTopEnd: number
startedAt?: number
start: () => void
stop: () => void
}
export type TimelineScrollMetrics = {
frameCount: number
frameGapMedianMs: number | null
frameGapP95Ms: number | null
frameGapMaxMs: number | null
longTaskCount: number
longTaskTotalMs: number
maxLongTaskMs: number
scrollEvents: number
scrolledPx: number
}
/** Records scroll-path frame pacing and long tasks across the measured scroll window. */
export async function installTimelineScrollProbe(page: Page) {
await page.evaluate((selector) => {
const root = [...document.querySelectorAll<HTMLElement>(selector)].find((element) =>
element.querySelector("[data-timeline-row]"),
)
if (!root) throw new Error("timeline scroller is not mounted")
const probe: TimelineScrollProbe = {
frames: [],
longTasks: [],
scrollEvents: 0,
scrollTopStart: 0,
scrollTopEnd: 0,
start: () => {
probe.startedAt = performance.now()
probe.scrollTopStart = root.scrollTop
requestAnimationFrame(frame)
},
stop: () => {
probe.startedAt = undefined
observer?.disconnect()
probe.scrollTopEnd = root.scrollTop
},
}
const observer = PerformanceObserver.supportedEntryTypes.includes("longtask")
? new PerformanceObserver((list) => {
probe.longTasks.push(
...list.getEntries().map((entry) => ({ startTime: entry.startTime, duration: entry.duration })),
)
})
: undefined
observer?.observe({ type: "longtask" })
function frame(time: number) {
if (probe.startedAt === undefined) return
probe.frames.push(time)
requestAnimationFrame(frame)
}
root.addEventListener(
"scroll",
() => {
if (probe.startedAt === undefined) return
probe.scrollEvents += 1
},
{ passive: true },
)
;(window as Window & { __timelineScrollProbe?: TimelineScrollProbe }).__timelineScrollProbe = probe
}, scrollerSelector)
}
export async function startTimelineScrollProbe(page: Page) {
await page.evaluate(() => {
;(window as Window & { __timelineScrollProbe?: TimelineScrollProbe }).__timelineScrollProbe!.start()
})
}
export async function collectTimelineScrollMetrics(page: Page): Promise<TimelineScrollMetrics> {
return page.evaluate(() => {
const probe = (window as Window & { __timelineScrollProbe?: TimelineScrollProbe }).__timelineScrollProbe!
const startedAt = probe.startedAt!
const endedAt = performance.now()
probe.stop()
const frames = probe.frames
const gaps = frames.map((time, index) => time - (frames[index - 1] ?? time)).filter((gap) => gap > 0)
const longTasks = probe.longTasks.filter((entry) => entry.startTime >= startedAt && entry.startTime <= endedAt)
return {
frameCount: frames.length,
frameGapMedianMs: median(gaps),
frameGapP95Ms: nearestRank(gaps, 0.95),
frameGapMaxMs: gaps.length === 0 ? null : Math.max(...gaps),
longTaskCount: longTasks.length,
longTaskTotalMs: longTasks.reduce((sum, entry) => sum + entry.duration, 0),
maxLongTaskMs: longTasks.length === 0 ? 0 : Math.max(...longTasks.map((entry) => entry.duration)),
scrollEvents: probe.scrollEvents,
scrolledPx: Math.abs(probe.scrollTopEnd - probe.scrollTopStart),
}
function median(values: number[]) {
if (values.length === 0) return null
const sorted = [...values].sort((a, b) => a - b)
const middle = Math.floor(sorted.length / 2)
return sorted.length % 2 === 0 ? (sorted[middle - 1]! + sorted[middle]!) / 2 : sorted[middle]!
}
function nearestRank(values: number[], quantile: number) {
if (values.length === 0) return null
const sorted = [...values].sort((a, b) => a - b)
return sorted[Math.min(sorted.length, Math.max(1, Math.ceil(quantile * sorted.length))) - 1]!
}
})
}
Original file line number
Diff line number
Diff line change
Expand Up
@@ -47,7 +47,9 @@ export function createSessionTimelineInteraction(session: SessionModel) {
const pin = () => setState("follow", { sessionKey: session.identity.sessionKey(), pinned: true })
const unpin = () => {
if (!scroller || scroller.scrollHeight - scroller.clientHeight <= 1) return
// Already unpinned: the geometry read cannot change the outcome.
if (!pinned()) return
if (!scroller || !scrollGeometry(scroller).overflow) return
setState("follow", { sessionKey: session.identity.sessionKey(), pinned: false })
}
Expand Down
Expand Up
@@ -109,16 +111,22 @@ export function createSessionTimelineInteraction(session: SessionModel) {
setState("messageID", message?.id)
}
const jumpThreshold = (element: HTMLDivElement) => Math.max(400, element.clientHeight)
// The scroll path reads geometry from several call sites, and each read can force a
// synchronous layout. Read each property once and derive the shared values here.
const scrollGeometry = (element: HTMLDivElement) => {
const clientHeight = element.clientHeight
const max = element.scrollHeight - clientHeight
return { clientHeight, max, overflow: max > 1 }
}
const updateScrollState = (element: HTMLDivElement) => {
const max = element.scrollHeight - element.clientHeight
const distance = max - element.scrollTop
const overflow = max > 1
const jump = overflow && distance > jumpThreshold(element)
const geometry = scrollGeometry(element)
const distance = geometry.max - element.scrollTop
const jump = geometry.overflow && distance > Math.max(400, geometry.clientHeight)
if (state.scroll.overflow === overflow && state.scroll.jump === jump) return
setState("scroll", { overflow, jump })
if (state.scroll.overflow === geometry. overflow && state.scroll.jump === jump) return
setState("scroll", { overflow: geometry.overflow , jump })
}
const scheduleScrollState = (element: HTMLDivElement) => {
Expand Down
Expand Up
@@ -259,7 +267,7 @@ export function createSessionTimelineInteraction(session: SessionModel) {
if (!pinned() || timeline.history.loading() || !scroller) return
if (scroller.scrollHeight > scroller.clientHeight + 1 || !timeline.history.more()) return
if (scrollGeometry( scroller).overflow || !timeline.history.more()) return
void loadOlder()
})
}
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -803,6 +803,7 @@ export function createTimelineVirtualizer(input: Input) {
width: "100%",
height: `${item().size}px`,
overflow: "clip",
contain: "layout paint",
"overflow-clip-margin": Predicate.isTagged(row(), "TurnGap") ? undefined : "0.5px",
}}
>
Expand Down
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.