fix(renderer): drive agent working spinner on the compositor (STA-3328) (#12359)
* fix(renderer): drive agent working spinner on the compositor (STA-3328) The shared 12Hz JS clock wrote el.style.transform on every mounted spinner (41 live = ~490 main-thread style writes/s), keeping style perpetually dirty and delaying keystroke dispatch (measured typing inputDelay p90 363ms; 19ms with the writes stopped). Replace it with a steps(12) CSS transform animation so rotation runs on the compositor; one mount-time animation-delay write preserves the shared-epoch phase sync. * fix(renderer): lock agent spinner phases to document time * fix(renderer): tolerate missing spinner animation API
This commit is contained in:
@@ -1455,6 +1455,26 @@ html.native-shell .app-layout {
|
||||
grid-template-rows: 1fr;
|
||||
}
|
||||
|
||||
/* Why: must stay a compositor-driven CSS animation — a JS clock writing
|
||||
per-element transforms blocks the renderer input thread (STA-3328: 41
|
||||
spinners ⇒ ~490 style writes/s, keystroke p90 363ms). The component anchors
|
||||
each animation's startTime once; steps(12) preserves the retired cadence. */
|
||||
@keyframes agent-spinner-rotate {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.agent-working-spinner {
|
||||
animation: agent-spinner-rotate 1s steps(12, end) infinite;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.agent-working-spinner {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* Why: keyframes run when the content mounts already in its final state. */
|
||||
@keyframes compact-agent-expansion-reveal {
|
||||
from {
|
||||
|
||||
@@ -22,15 +22,13 @@ describe('AgentStateDot', () => {
|
||||
|
||||
expect(markup).toContain('border-yellow-500')
|
||||
expect(markup).toContain('border-t-transparent')
|
||||
// Why: rotation comes from the shared agent-spinner clock (which also
|
||||
// honors prefers-reduced-motion), not a per-element CSS animation that
|
||||
// would keep the compositor awake.
|
||||
// Why: rotation must come from the compositor-driven CSS animation, not a
|
||||
// JS clock writing per-element styles on the input thread (STA-3328).
|
||||
expect(markup).toContain('agent-working-spinner')
|
||||
expect(markup).toContain('data-agent-spinner')
|
||||
// Why: under reduced motion the top border is filled so the static ring
|
||||
// reads as a complete marker, not a broken partial spinner (#9515).
|
||||
expect(markup).toContain('motion-reduce:border-t-yellow-500')
|
||||
expect(markup).not.toContain('animate-spin')
|
||||
expect(markup).not.toContain('animation:spin')
|
||||
})
|
||||
|
||||
it('renders done as an emerald check icon', () => {
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import React, { act } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { AgentWorkingSpinner } from './AgentWorkingSpinner'
|
||||
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
|
||||
describe('AgentWorkingSpinner', () => {
|
||||
it('hooks the compositor-driven CSS animation, not a JS clock', () => {
|
||||
const markup = renderToStaticMarkup(React.createElement(AgentWorkingSpinner))
|
||||
|
||||
expect(markup).toContain('agent-working-spinner')
|
||||
expect(markup).toContain('data-agent-spinner')
|
||||
expect(markup).toContain('border-yellow-500')
|
||||
expect(markup).toContain('border-t-transparent')
|
||||
expect(markup).toContain('motion-reduce:border-t-yellow-500')
|
||||
})
|
||||
|
||||
it('renders when the Web Animations API is unavailable', async () => {
|
||||
const originalGetAnimations = Object.getOwnPropertyDescriptor(
|
||||
HTMLElement.prototype,
|
||||
'getAnimations'
|
||||
)
|
||||
Object.defineProperty(HTMLElement.prototype, 'getAnimations', {
|
||||
configurable: true,
|
||||
value: undefined
|
||||
})
|
||||
const container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
const root = createRoot(container)
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
root.render(<AgentWorkingSpinner />)
|
||||
})
|
||||
expect(container.querySelector('[data-agent-spinner]')).not.toBeNull()
|
||||
} finally {
|
||||
act(() => root.unmount())
|
||||
container.remove()
|
||||
if (originalGetAnimations === undefined) {
|
||||
Reflect.deleteProperty(HTMLElement.prototype, 'getAnimations')
|
||||
} else {
|
||||
Object.defineProperty(HTMLElement.prototype, 'getAnimations', originalGetAnimations)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('anchors mount and restart animations to the shared document epoch', async () => {
|
||||
const animation = {
|
||||
animationName: 'agent-spinner-rotate',
|
||||
startTime: 321
|
||||
} as unknown as Animation
|
||||
const getAnimations = vi.fn(() => [animation])
|
||||
const originalGetAnimations = Object.getOwnPropertyDescriptor(
|
||||
HTMLElement.prototype,
|
||||
'getAnimations'
|
||||
)
|
||||
Object.defineProperty(HTMLElement.prototype, 'getAnimations', {
|
||||
configurable: true,
|
||||
value: getAnimations
|
||||
})
|
||||
const container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
const root = createRoot(container)
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
root.render(<AgentWorkingSpinner />)
|
||||
})
|
||||
expect(animation.startTime).toBe(0)
|
||||
|
||||
animation.startTime = 654
|
||||
const restart = new Event('animationstart', { bubbles: true })
|
||||
Object.defineProperty(restart, 'animationName', { value: 'agent-spinner-rotate' })
|
||||
await act(async () => {
|
||||
container.querySelector('[data-agent-spinner]')!.dispatchEvent(restart)
|
||||
})
|
||||
expect(animation.startTime).toBe(0)
|
||||
expect(getAnimations).toHaveBeenCalledTimes(2)
|
||||
} finally {
|
||||
act(() => root.unmount())
|
||||
container.remove()
|
||||
if (originalGetAnimations === undefined) {
|
||||
Reflect.deleteProperty(HTMLElement.prototype, 'getAnimations')
|
||||
} else {
|
||||
Object.defineProperty(HTMLElement.prototype, 'getAnimations', originalGetAnimations)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Why: the class only spins if main.css defines it — pin the wiring across
|
||||
// both files so neither side can be renamed or dropped alone (STA-3328
|
||||
// regressed typing latency when rotation moved onto the input thread).
|
||||
it('is backed by a steps(12) keyframe animation in main.css', () => {
|
||||
const css = readFileSync(join(__dirname, '../assets/main.css'), 'utf8')
|
||||
|
||||
const rule = css.match(/\.agent-working-spinner\s*\{[^}]*\}/)?.[0]
|
||||
expect(rule).toBeDefined()
|
||||
expect(rule).toContain('animation: agent-spinner-rotate 1s steps(12, end) infinite')
|
||||
expect(css).toContain('@keyframes agent-spinner-rotate')
|
||||
|
||||
const reducedMotionBlock = css.match(
|
||||
/@media \(prefers-reduced-motion: reduce\)\s*\{\s*\.agent-working-spinner\s*\{[^}]*\}/
|
||||
)?.[0]
|
||||
expect(reducedMotionBlock).toContain('animation: none')
|
||||
})
|
||||
})
|
||||
@@ -1,21 +1,46 @@
|
||||
import React from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { agentSpinnerRef } from '@/lib/agent-spinner-clock'
|
||||
|
||||
// Why: the working-state ring must not carry its own infinite CSS animation —
|
||||
// that keeps the compositor awake per element for the whole agent run. The
|
||||
// shared agent-spinner clock rotates every mounted ring in phase and stops
|
||||
// cleanly when nothing can be seen. Callers size it via className (size-2 etc.).
|
||||
const SPINNER_ANIMATION_NAME = 'agent-spinner-rotate'
|
||||
|
||||
// Why: CSS assigns per-element start times after refs run; anchoring the Web
|
||||
// Animation timeline gives late mounts exact phase sync without recurring JS.
|
||||
function syncSpinnerPhase(el: HTMLSpanElement | null): void {
|
||||
if (el === null || typeof el.getAnimations !== 'function') {
|
||||
return
|
||||
}
|
||||
|
||||
const animation = el
|
||||
.getAnimations()
|
||||
.find(
|
||||
(candidate) =>
|
||||
'animationName' in candidate && candidate.animationName === SPINNER_ANIMATION_NAME
|
||||
)
|
||||
if (animation !== undefined) {
|
||||
animation.startTime = 0
|
||||
}
|
||||
}
|
||||
|
||||
function handleSpinnerAnimationStart(event: React.AnimationEvent<HTMLSpanElement>): void {
|
||||
if (event.animationName === SPINNER_ANIMATION_NAME) {
|
||||
syncSpinnerPhase(event.currentTarget)
|
||||
}
|
||||
}
|
||||
|
||||
// Why: the working-state ring animates via CSS (.agent-working-spinner in
|
||||
// main.css) so rotation runs on the compositor and never touches the input
|
||||
// thread. Callers size it via className (size-2 etc.).
|
||||
export function AgentWorkingSpinner({ className }: { className?: string }): React.JSX.Element {
|
||||
return (
|
||||
<span
|
||||
ref={agentSpinnerRef}
|
||||
ref={syncSpinnerPhase}
|
||||
onAnimationStart={handleSpinnerAnimationStart}
|
||||
data-agent-spinner=""
|
||||
className={cn(
|
||||
// Why: under reduced motion the clock never ticks, so fill the top
|
||||
// Why: under reduced motion the animation is disabled, so fill the top
|
||||
// border too — a frozen transparent-top ring reads as a broken
|
||||
// spinner; a complete ring reads as an intentional static marker (#9515).
|
||||
'block rounded-full border-2 border-yellow-500 border-t-transparent motion-reduce:border-t-yellow-500',
|
||||
'agent-working-spinner block rounded-full border-2 border-yellow-500 border-t-transparent motion-reduce:border-t-yellow-500',
|
||||
className
|
||||
)}
|
||||
/>
|
||||
|
||||
@@ -17,19 +17,18 @@ function renderDotClassNames(status: Status): string[] {
|
||||
}
|
||||
|
||||
describe('StatusIndicator', () => {
|
||||
it('renders working as a clock-driven yellow spinner ring', () => {
|
||||
it('renders working as a yellow spinner ring', () => {
|
||||
const markup = renderMarkup('working')
|
||||
|
||||
expect(markup).toContain('border-yellow-500')
|
||||
expect(markup).toContain('border-t-transparent')
|
||||
// Why: rotation comes from the shared agent-spinner clock, not a
|
||||
// per-element CSS animation that would keep the compositor awake.
|
||||
// Why: rotation must come from the compositor-driven CSS animation, not a
|
||||
// JS clock writing per-element styles on the input thread (STA-3328).
|
||||
expect(markup).toContain('agent-working-spinner')
|
||||
expect(markup).toContain('data-agent-spinner')
|
||||
// Why: under reduced motion the top border is filled so the static ring
|
||||
// reads as a complete marker, not a broken partial spinner (#9515).
|
||||
expect(markup).toContain('motion-reduce:border-t-yellow-500')
|
||||
expect(markup).not.toContain('animate-spin')
|
||||
expect(markup).not.toContain('animation:spin')
|
||||
})
|
||||
|
||||
it('renders permission as an amber question glyph', () => {
|
||||
|
||||
@@ -1,141 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
AGENT_SPINNER_TICK_MS,
|
||||
registerAgentSpinnerElement,
|
||||
resetAgentSpinnerClockForTesting
|
||||
} from './agent-spinner-clock'
|
||||
import { resetStaleDocumentVisibilityForTesting } from '@/components/terminal-pane/stale-document-visibility'
|
||||
|
||||
type FakeElement = { style: { transform: string } }
|
||||
|
||||
function makeElement(): HTMLElement {
|
||||
return { style: { transform: '' } } as unknown as HTMLElement
|
||||
}
|
||||
|
||||
function stubDom(visibilityState: () => DocumentVisibilityState): {
|
||||
fireVisibilityChange: () => void
|
||||
} {
|
||||
const documentListeners = new Map<string, Set<(event?: unknown) => void>>()
|
||||
const addListener = (event: string, listener: (event?: unknown) => void): void => {
|
||||
if (!documentListeners.has(event)) {
|
||||
documentListeners.set(event, new Set())
|
||||
}
|
||||
documentListeners.get(event)!.add(listener)
|
||||
}
|
||||
vi.stubGlobal('document', {
|
||||
get visibilityState() {
|
||||
return visibilityState()
|
||||
},
|
||||
addEventListener: vi.fn(addListener),
|
||||
removeEventListener: vi.fn((event: string, listener: (event?: unknown) => void) => {
|
||||
documentListeners.get(event)?.delete(listener)
|
||||
})
|
||||
})
|
||||
vi.stubGlobal('window', {
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
matchMedia: vi.fn(() => ({
|
||||
matches: false,
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn()
|
||||
}))
|
||||
})
|
||||
return {
|
||||
fireVisibilityChange: () => {
|
||||
for (const listener of documentListeners.get('visibilitychange') ?? []) {
|
||||
listener()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe('agent-spinner-clock', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
resetAgentSpinnerClockForTesting()
|
||||
resetStaleDocumentVisibilityForTesting()
|
||||
vi.useRealTimers()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('rotates every registered element in phase from one shared timer', () => {
|
||||
stubDom(() => 'visible')
|
||||
const a = makeElement()
|
||||
const unregisterA = registerAgentSpinnerElement(a)
|
||||
|
||||
// Registration seeds the current dial position immediately.
|
||||
expect((a as unknown as FakeElement).style.transform).toMatch(/^rotate\(\d+deg\)$/)
|
||||
|
||||
vi.advanceTimersByTime(AGENT_SPINNER_TICK_MS * 3)
|
||||
const b = makeElement()
|
||||
const unregisterB = registerAgentSpinnerElement(b)
|
||||
|
||||
// A late joiner starts at the shared dial position, not at zero.
|
||||
expect((b as unknown as FakeElement).style.transform).toBe(
|
||||
(a as unknown as FakeElement).style.transform
|
||||
)
|
||||
|
||||
const before = (a as unknown as FakeElement).style.transform
|
||||
vi.advanceTimersByTime(AGENT_SPINNER_TICK_MS)
|
||||
expect((a as unknown as FakeElement).style.transform).not.toBe(before)
|
||||
expect((b as unknown as FakeElement).style.transform).toBe(
|
||||
(a as unknown as FakeElement).style.transform
|
||||
)
|
||||
|
||||
unregisterA()
|
||||
unregisterB()
|
||||
})
|
||||
|
||||
it('stops ticking while the document is hidden and resumes on visibility', () => {
|
||||
let visibility: DocumentVisibilityState = 'visible'
|
||||
const { fireVisibilityChange } = stubDom(() => visibility)
|
||||
const el = makeElement()
|
||||
const unregister = registerAgentSpinnerElement(el)
|
||||
|
||||
visibility = 'hidden'
|
||||
fireVisibilityChange()
|
||||
const frozen = (el as unknown as FakeElement).style.transform
|
||||
vi.advanceTimersByTime(AGENT_SPINNER_TICK_MS * 10)
|
||||
expect((el as unknown as FakeElement).style.transform).toBe(frozen)
|
||||
|
||||
visibility = 'visible'
|
||||
fireVisibilityChange()
|
||||
// Resume advances immediately so the restored window visibly spins again.
|
||||
expect((el as unknown as FakeElement).style.transform).not.toBe(frozen)
|
||||
|
||||
unregister()
|
||||
})
|
||||
|
||||
it('clears its timer when the last element unregisters', () => {
|
||||
stubDom(() => 'visible')
|
||||
const el = makeElement()
|
||||
const unregister = registerAgentSpinnerElement(el)
|
||||
unregister()
|
||||
|
||||
const parked = (el as unknown as FakeElement).style.transform
|
||||
vi.advanceTimersByTime(AGENT_SPINNER_TICK_MS * 5)
|
||||
expect((el as unknown as FakeElement).style.transform).toBe(parked)
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
})
|
||||
|
||||
it('does not tick when prefers-reduced-motion is set', () => {
|
||||
stubDom(() => 'visible')
|
||||
const windowStub = globalThis.window as unknown as { matchMedia: ReturnType<typeof vi.fn> }
|
||||
windowStub.matchMedia = vi.fn(() => ({
|
||||
matches: true,
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn()
|
||||
}))
|
||||
|
||||
const el = makeElement()
|
||||
const unregister = registerAgentSpinnerElement(el)
|
||||
const initial = (el as unknown as FakeElement).style.transform
|
||||
vi.advanceTimersByTime(AGENT_SPINNER_TICK_MS * 5)
|
||||
expect((el as unknown as FakeElement).style.transform).toBe(initial)
|
||||
|
||||
unregister()
|
||||
})
|
||||
})
|
||||
@@ -1,128 +0,0 @@
|
||||
// Why: a per-element infinite CSS animation keeps Chromium's frame pipeline
|
||||
// awake the whole time any agent spinner is visible (~23.5ms CPU/s measured
|
||||
// live, nearly independent of cadence, scaling per element). Background
|
||||
// throttling only helps hidden windows — a visible sidebar full of working
|
||||
// agents pays continuously. One shared low-rate clock steps every registered
|
||||
// spinner element's transform directly, so the renderer idles between ticks
|
||||
// and costs the same whether one agent or fifty are working.
|
||||
import { isWindowVisible } from './window-visibility-interval'
|
||||
import {
|
||||
isDocumentVisibilityProvenStale,
|
||||
registerStaleDocumentVisibilityRecovery
|
||||
} from '@/components/terminal-pane/stale-document-visibility'
|
||||
|
||||
const SPIN_STEP_DEGREES = 30
|
||||
const SPIN_STEPS = 360 / SPIN_STEP_DEGREES
|
||||
// Why: 12 steps/s at 30° matches the retired CSS animation exactly — slower
|
||||
// cadences read as sluggish next to it. The win over CSS is structural (idle
|
||||
// between ticks, one timer for N spinners), not the tick rate.
|
||||
export const AGENT_SPINNER_TICK_MS = 1000 / 12
|
||||
|
||||
const elements = new Set<HTMLElement>()
|
||||
let timer: ReturnType<typeof setInterval> | null = null
|
||||
let step = 0
|
||||
let teardownGlobalListeners: (() => void) | null = null
|
||||
|
||||
function currentTransform(): string {
|
||||
return `rotate(${step * SPIN_STEP_DEGREES}deg)`
|
||||
}
|
||||
|
||||
function tick(): void {
|
||||
step = (step + 1) % SPIN_STEPS
|
||||
const transform = currentTransform()
|
||||
for (const el of elements) {
|
||||
el.style.transform = transform
|
||||
}
|
||||
}
|
||||
|
||||
function prefersReducedMotion(): boolean {
|
||||
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {
|
||||
return false
|
||||
}
|
||||
return window.matchMedia('(prefers-reduced-motion: reduce)').matches
|
||||
}
|
||||
|
||||
function shouldRun(): boolean {
|
||||
// Why: the stale-visibility latch proves user input arrived while the macOS
|
||||
// occlusion tracker still claims hidden — keep spinning for the user we know
|
||||
// is watching instead of freezing until the tracker recovers.
|
||||
const visible = isWindowVisible() || isDocumentVisibilityProvenStale()
|
||||
return elements.size > 0 && visible && !prefersReducedMotion()
|
||||
}
|
||||
|
||||
function reconcile(): void {
|
||||
if (shouldRun()) {
|
||||
if (timer === null) {
|
||||
// Advance immediately so a just-restored window visibly resumes.
|
||||
tick()
|
||||
timer = setInterval(tick, AGENT_SPINNER_TICK_MS)
|
||||
}
|
||||
return
|
||||
}
|
||||
if (timer !== null) {
|
||||
clearInterval(timer)
|
||||
timer = null
|
||||
}
|
||||
}
|
||||
|
||||
function installGlobalListeners(): void {
|
||||
if (
|
||||
teardownGlobalListeners !== null ||
|
||||
typeof document === 'undefined' ||
|
||||
typeof document.addEventListener !== 'function'
|
||||
) {
|
||||
return
|
||||
}
|
||||
const onSignal = (): void => {
|
||||
reconcile()
|
||||
}
|
||||
document.addEventListener('visibilitychange', onSignal)
|
||||
const reducedMotionQuery =
|
||||
typeof window !== 'undefined' && typeof window.matchMedia === 'function'
|
||||
? window.matchMedia('(prefers-reduced-motion: reduce)')
|
||||
: null
|
||||
reducedMotionQuery?.addEventListener?.('change', onSignal)
|
||||
const unregisterStaleRecovery = registerStaleDocumentVisibilityRecovery(onSignal)
|
||||
teardownGlobalListeners = () => {
|
||||
document.removeEventListener('visibilitychange', onSignal)
|
||||
reducedMotionQuery?.removeEventListener?.('change', onSignal)
|
||||
unregisterStaleRecovery()
|
||||
}
|
||||
}
|
||||
|
||||
export function registerAgentSpinnerElement(el: HTMLElement): () => void {
|
||||
elements.add(el)
|
||||
// Join in phase with the shared dial so late-mounting spinners stay in sync.
|
||||
el.style.transform = currentTransform()
|
||||
installGlobalListeners()
|
||||
reconcile()
|
||||
return () => {
|
||||
elements.delete(el)
|
||||
reconcile()
|
||||
if (elements.size === 0 && teardownGlobalListeners !== null) {
|
||||
teardownGlobalListeners()
|
||||
teardownGlobalListeners = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Stable React ref callback: attach to a spinner element to spin it. */
|
||||
export function agentSpinnerRef(el: HTMLElement | null): (() => void) | undefined {
|
||||
if (el === null) {
|
||||
return undefined
|
||||
}
|
||||
return registerAgentSpinnerElement(el)
|
||||
}
|
||||
|
||||
export function resetAgentSpinnerClockForTesting(): void {
|
||||
if (timer !== null) {
|
||||
clearInterval(timer)
|
||||
timer = null
|
||||
}
|
||||
elements.clear()
|
||||
if (teardownGlobalListeners !== null) {
|
||||
teardownGlobalListeners()
|
||||
teardownGlobalListeners = null
|
||||
}
|
||||
step = 0
|
||||
}
|
||||
Reference in New Issue
Block a user