perf(renderer): stop agent spinners that are scrolled out of view (#37153)

Offscreen or clipped working rings dropped their CSS animation through one
shared IntersectionObserver; revealing a ring restarts it and the existing
animationstart anchor keeps every ring on the shared phase.

The spinner bench gains an always-on comparison variant and reports
compositor frame counts.
This commit is contained in:
Neil
2026-11-01 16:05:02 -08:00
committed by GitHub
parent b6467f0577
commit ec112c6b01
7 changed files with 149 additions and 2 deletions
+4
View File
@@ -1819,6 +1819,10 @@ html.native-shell .app-layout {
animation: agent-spinner-rotate 86400s steps(1036800, end) infinite;
}
.agent-working-spinner[data-animation-offscreen] {
animation: none;
}
@media (prefers-reduced-motion: reduce) {
.agent-working-spinner {
animation: none;
@@ -1,5 +1,6 @@
import React from 'react'
import { cn } from '@/lib/utils'
import { observeOffscreenAnimation } from '@/lib/offscreen-animation-pause'
const SPINNER_ANIMATION_NAME = 'agent-spinner-rotate'
@@ -26,10 +27,16 @@ function handleSpinnerAnimationStart(event: React.AnimationEvent<HTMLSpanElement
}
}
// Offscreen rings drop their animation; the restart on reveal re-anchors phase via animationstart.
function observeSpinner(el: HTMLSpanElement): () => void {
return observeOffscreenAnimation(el)
}
// CSS compositor rotation avoids JS input-thread work; callers provide size.
export function AgentWorkingSpinner({ className }: { className?: string }): React.JSX.Element {
return (
<span
ref={observeSpinner}
onAnimationStart={handleSpinnerAnimationStart}
data-agent-spinner=""
className={cn(
@@ -0,0 +1,64 @@
// @vitest-environment happy-dom
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
OFFSCREEN_ANIMATION_ATTRIBUTE,
observeOffscreenAnimation
} from './offscreen-animation-pause'
type Callback = (entries: Pick<IntersectionObserverEntry, 'target' | 'isIntersecting'>[]) => void
const observers: { callback: Callback; disconnect: ReturnType<typeof vi.fn> }[] = []
class FakeIntersectionObserver {
observe = vi.fn()
unobserve = vi.fn()
disconnect = vi.fn()
constructor(callback: Callback) {
observers.push({ callback, disconnect: this.disconnect })
}
}
describe('observeOffscreenAnimation', () => {
afterEach(() => {
observers.length = 0
vi.unstubAllGlobals()
})
it('marks elements only while they are outside the viewport', () => {
vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver)
const element = document.createElement('span')
const release = observeOffscreenAnimation(element)
observers[0].callback([{ target: element, isIntersecting: false }])
expect(element.hasAttribute(OFFSCREEN_ANIMATION_ATTRIBUTE)).toBe(true)
observers[0].callback([{ target: element, isIntersecting: true }])
expect(element.hasAttribute(OFFSCREEN_ANIMATION_ATTRIBUTE)).toBe(false)
observers[0].callback([{ target: element, isIntersecting: false }])
release()
expect(element.hasAttribute(OFFSCREEN_ANIMATION_ATTRIBUTE)).toBe(false)
})
it('shares one observer and disconnects it after the last release', () => {
vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver)
const releaseFirst = observeOffscreenAnimation(document.createElement('span'))
const releaseSecond = observeOffscreenAnimation(document.createElement('span'))
expect(observers).toHaveLength(1)
releaseFirst()
expect(observers[0].disconnect).not.toHaveBeenCalled()
releaseSecond()
expect(observers[0].disconnect).toHaveBeenCalledOnce()
observeOffscreenAnimation(document.createElement('span'))()
expect(observers).toHaveLength(2)
})
it('leaves animations running where IntersectionObserver is unavailable', () => {
vi.stubGlobal('IntersectionObserver', undefined)
const element = document.createElement('span')
observeOffscreenAnimation(element)()
expect(element.hasAttribute(OFFSCREEN_ANIMATION_ATTRIBUTE)).toBe(false)
})
})
@@ -0,0 +1,36 @@
// Running CSS animations make the compositor tick every refresh even when scrolled out of view or clipped.
export const OFFSCREEN_ANIMATION_ATTRIBUTE = 'data-animation-offscreen'
let observer: IntersectionObserver | null = null
let observedCount = 0
function getObserver(): IntersectionObserver | null {
if (typeof IntersectionObserver !== 'function') {
return null
}
observer ??= new IntersectionObserver((entries) => {
for (const entry of entries) {
entry.target.toggleAttribute(OFFSCREEN_ANIMATION_ATTRIBUTE, !entry.isIntersecting)
}
})
return observer
}
/** Marks the element while it is outside the viewport so CSS can stop its animation. */
export function observeOffscreenAnimation(element: Element): () => void {
const shared = getObserver()
if (shared === null) {
return () => {}
}
shared.observe(element)
observedCount++
return () => {
shared.unobserve(element)
element.removeAttribute(OFFSCREEN_ANIMATION_ATTRIBUTE)
observedCount--
if (observedCount === 0) {
shared.disconnect()
observer = null
}
}
}
@@ -4,6 +4,12 @@ export const spinnerVariants = {
.agent-working-spinner { animation-duration: 1s; animation-timing-function: steps(12, end); }
`,
long: '',
// Keeps scrolled-out rings animating, as before offscreen pausing.
unpaused: `
.agent-working-spinner[data-animation-offscreen] {
animation: agent-spinner-rotate 86400s steps(1036800, end) infinite;
}
`,
// Retain the rejected containment experiment for reproducible ablation.
contained:
'.spinner-benchmark-container { content-visibility: auto; overflow-clip-margin: var(--spacing); }'
@@ -2,7 +2,7 @@ import { writeFileSync } from 'node:fs'
export async function traceIterations(cdp, outputPath, durationMs = 2200) {
await cdp.send('Tracing.start', {
categories: 'devtools.timeline',
categories: 'devtools.timeline,toplevel,cc,disabled-by-default-cc.debug.scheduler',
transferMode: 'ReturnAsStream'
})
await new Promise((resolve) => setTimeout(resolve, durationMs))
@@ -23,11 +23,33 @@ export async function traceIterations(cdp, outputPath, durationMs = 2200) {
}
writeFileSync(outputPath, json)
const events = JSON.parse(json).traceEvents
const compositorThreads = new Set(
events
.filter((event) => event.name === 'thread_name' && event.args?.name === 'Compositor')
.map((event) => `${event.pid}:${event.tid}`)
)
const onCompositor = events.filter((event) => compositorThreads.has(`${event.pid}:${event.tid}`))
const perSecond = (count) => Math.round((count * 1000) / durationMs)
return {
durationMs,
iterationEvents: events.filter(
(event) => event.name === 'EventDispatch' && event.args?.data?.type === 'animationiteration'
).length,
styleUpdates: events.filter((event) => event.name === 'UpdateLayoutTree').length
styleUpdates: events.filter((event) => event.name === 'UpdateLayoutTree').length,
// A spinner that wakes the compositor every refresh shows up as many no-damage frames.
compositorFramesPerSecond: perSecond(
onCompositor.filter((event) => event.name === 'Scheduler::BeginImplFrame').length
),
noDamageFramesPerSecond: perSecond(
onCompositor.filter((event) => event.name === 'EarlyOut_NoDamage').length
),
compositorThreadMsPerSecond:
Math.round(
(onCompositor
.filter((event) => event.name === 'ThreadControllerImpl::RunTask')
.reduce((total, event) => total + (event.tdur ?? event.dur ?? 0), 0) /
durationMs) *
10
) / 10
}
}
@@ -6,6 +6,10 @@ async function waitForPhase(page) {
.waitForFunction(() =>
[...document.querySelectorAll('[data-agent-spinner]')].every((element) => {
const animations = element.getAnimations({ subtree: true })
// Offscreen rings must hold no animation; onscreen ones run on the shared phase.
if (element.hasAttribute('data-animation-offscreen')) {
return animations.length === 0
}
return (
animations.length === 1 &&
animations[0].startTime === 0 &&
@@ -53,6 +57,9 @@ export async function verifyRendering(app, page, outputDir) {
await page.emulateMedia({ reducedMotion: 'no-preference' })
await waitForPhase(page)
await page.evaluate(() => window.spinnerBenchmark.render({ count: 200, offset: 5000 }))
await page.waitForFunction(
() => document.querySelectorAll('[data-agent-spinner][data-animation-offscreen]').length === 200
)
await waitForPhase(page)
await page.evaluate(() => {
document.querySelector('#scroller').scrollTop = 5000
@@ -104,6 +111,7 @@ export async function verifyRendering(app, page, outputDir) {
)
return {
pixelComparisons,
offscreenPause: true,
iterationEvents,
phases: true,
reducedMotion: true,