Skip to content

The agent that grows with you

perf(desktop): drop the loader clock-pause; coalesce composer measures via rafCoalesce; one decode-cursor keyframe

kshitijk4poorba4c0fbbdc72
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-metrics.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-metrics.test.tsx
index cf082d02026..450669c4f9e 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-metrics.test.tsx
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-metrics.test.tsx
@@ -1,4 +1,4 @@
-import { cleanup, render } from '@testing-library/react'
+import { act, cleanup, render } from '@testing-library/react'
import { type RefObject, StrictMode, useRef } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -35,6 +35,8 @@ class FakeResizeObserver implements ResizeObserver {
}
}
+// Measurements coalesce into one requestAnimationFrame (#99889), so a delivered
+// resize is observable only after the frame runs.
const deliverResize = () => {
for (const observer of observers) {
const entries = [...observer.targets].map(target => ({ target }) as ResizeObserverEntry)
@@ -43,6 +45,10 @@ const deliverResize = () => {
observer.callback(entries, observer)
}
}
+
+ act(() => {
+ vi.advanceTimersToNextFrame()
+ })
}
const sized =
@@ -82,12 +88,34 @@ const surfaceOf = (container: HTMLElement) => container.querySelector<HTMLElemen
describe('useComposerMetrics — published clearance survives an effect replay', () => {
beforeEach(() => {
observers.length = 0
+ vi.useFakeTimers({ toFake: ['requestAnimationFrame', 'cancelAnimationFrame'] })
vi.stubGlobal('ResizeObserver', FakeResizeObserver)
})
afterEach(() => {
cleanup()
vi.unstubAllGlobals()
+ vi.useRealTimers()
+ })
+
+ it('coalesces a burst of resize notifications into one measurement per frame', () => {
+ const { container } = render(<Harness dockHeight={200} surfaceHeight={120} />)
+ deliverResize()
+ const dock = container.querySelector('form')!.parentElement!
+ const measure = vi.spyOn(dock, 'getBoundingClientRect')
+
+ for (const observer of observers) {
+ const entries = [...observer.targets].map(target => ({ target }) as ResizeObserverEntry)
+ observer.callback(entries, observer)
+ observer.callback(entries, observer)
+ observer.callback(entries, observer)
+ }
+
+ expect(measure).not.toHaveBeenCalled()
+ act(() => {
+ vi.advanceTimersToNextFrame()
+ })
+ expect(measure).toHaveBeenCalledTimes(1)
})
it('republishes the dock height after StrictMode replays the cleanup', () => {
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-metrics.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-metrics.ts
index 972e1f814b2..fd3a21d7a98 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-metrics.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-metrics.ts
@@ -1,5 +1,5 @@
import { useAuiState } from '@assistant-ui/react'
-import { type RefObject, useCallback, useEffect, useRef, useState } from 'react'
+import { type RefObject, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
chatSurfaceRoot,
@@ -9,6 +9,7 @@ import {
setSurfaceVar
} from '@/app/chat/surface-vars'
import { useResizeObserver } from '@/hooks/use-resize-observer'
+import { rafCoalesce } from '@/lib/raf-coalesce'
import {
COMPOSER_COMPACT_PILL_PX,
@@ -114,16 +115,8 @@ export function useComposerMetrics({
// would re-register the observation.
const poppedOutRef = useRef(poppedOut)
poppedOutRef.current = poppedOut
- // #99889: ResizeObserver loop guard — setSurfaceVar mutates a CSS var that
- // can change layout (thread clearance), which re-triggers the observer that
- // just wrote it. Without a frame gate the observer fires again inside the
- // same frame with undelivered notifications (see desktop.log) and the trace
- // shows ForcedStyleAndLayout UpdateTime 17k events. Coalesce all
- // measurements in one frame to a single rAF so at most one style invalidation
- // is scheduled per frame.
- const rafIdRef = useRef<number | null>(null)
-
- const doSyncComposerMetrics = useCallback(() => {
+
+ const measureComposerMetrics = useCallback(() => {
const composer = composerRef.current
// The dock is the full docked footprint — strips, status stack, composer —
// so it, not the composer alone, is what the thread has to clear.
@@ -188,30 +181,13 @@ export function useComposerMetrics({
}
}, [composerDockRef, composerRef, composerSurfaceRef, editorRef])
- const syncComposerMetrics = useCallback(() => {
- if (rafIdRef.current !== null) {
- return
- }
-
- rafIdRef.current = window.requestAnimationFrame(() => {
- rafIdRef.current = null
- doSyncComposerMetrics()
- })
- }, [doSyncComposerMetrics])
+ // setSurfaceVar changes layout, which re-fires the observer that wrote it; coalesce to one
+ // measurement per frame so at most one style invalidation is scheduled per frame (#99889).
+ const coalescedMeasure = useMemo(() => rafCoalesce<true>(() => measureComposerMetrics()), [measureComposerMetrics])
+ const syncComposerMetrics = useCallback(() => coalescedMeasure.push(true), [coalescedMeasure])
useResizeObserver(syncComposerMetrics, composerDockRef, composerRef, composerSurfaceRef, editorRef)
- // Cancel any pending rAF on unmount so a late frame doesn't write after detach
- // eslint-disable-next-line no-restricted-syntax -- rAF handle, not an atom mirror (see eslint rule comment)
- useEffect(() => {
- return () => {
- if (rafIdRef.current !== null) {
- cancelAnimationFrame(rafIdRef.current)
- rafIdRef.current = null
- }
- }
- }, [])
-
// Toggling pop-out changes whether the composer reserves thread clearance.
// The ResizeObserver may not fire (the box can keep the same box size), so
// re-sync explicitly: docked republishes the measured height, floating zeroes
@@ -228,6 +204,7 @@ export function useComposerMetrics({
const root = chatSurfaceRoot(composerRef.current)
return () => {
+ coalescedMeasure.cancel()
clearSurfaceVar(root, COMPOSER_HEIGHT_VAR)
clearSurfaceVar(root, COMPOSER_SURFACE_HEIGHT_VAR)
// The bucket refs mirror what is published, so clearing the vars must
@@ -241,7 +218,7 @@ export function useComposerMetrics({
lastBucketedHeightRef.current = 0
lastBucketedSurfaceHeightRef.current = 0
}
- }, [composerRef])
+ }, [coalescedMeasure, composerRef])
// Every decision comes from the composer's OWN measured width, never the
// viewport's. There used to be a `(max-width: 30rem)` media query in here as
diff --git a/apps/desktop/src/components/onboarding/glyph.tsx b/apps/desktop/src/components/onboarding/glyph.tsx
index ecee40730dc..ed72a09f3ca 100644
--- a/apps/desktop/src/components/onboarding/glyph.tsx
+++ b/apps/desktop/src/components/onboarding/glyph.tsx
@@ -127,7 +127,7 @@ export function DecodedLabel({ leaving, text }: { leaving?: boolean; text: strin
<GlyphText text={decoded} />
<span
aria-hidden="true"
- className="dither ml-1.5 -mr-[0.875rem] inline-block size-2 shrink-0 -translate-y-px rounded-[1px] text-primary ob-decode-cursor-blink"
+ className="dither ml-1.5 -mr-[0.875rem] inline-block size-2 shrink-0 -translate-y-px rounded-[1px] text-primary decode-cursor-blink"
/>
</span>
)
diff --git a/apps/desktop/src/components/ui/loader.test.tsx b/apps/desktop/src/components/ui/loader.test.tsx
deleted file mode 100644
index 500e87241fa..00000000000
--- a/apps/desktop/src/components/ui/loader.test.tsx
+++ /dev/null
@@ -1,146 +0,0 @@
-import { act } from 'react'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-
-import { reactRoot } from '@/test/react-root'
-import { setDocumentHidden } from '@/test/window-state'
-
-import { Loader } from './loader'
-
-const PAUSED_ATTRIBUTE = 'data-renderer-animations-paused'
-
-/**
- * The paused-time accounting in `Loader` is only meaningful against a clock the
- * test owns: Chromium throttles — and for a hidden document stops — rAF, so the
- * frame timestamps the loader receives are not evenly spaced. This harness hands
- * it exactly the timestamps we want, including a 60 s gap with no callbacks at
- * all, which is what a hidden tab actually looks like.
- */
-function installFrameClock() {
- let clock = 1_000
- let nextId = 1
- const frames = new Map<number, FrameRequestCallback>()
-
- vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
- const id = nextId++
-
- frames.set(id, callback)
-
- return id
- })
- vi.stubGlobal('cancelAnimationFrame', (id: number) => frames.delete(id))
- vi.spyOn(performance, 'now').mockImplementation(() => clock)
-
- return {
- /** Advance the clock and run the frames pending right now, like one rAF
- * turn: a callback that re-requests a frame lands in the next turn. */
- frame(now: number) {
- clock = now
-
- const pending = [...frames.values()]
-
- frames.clear()
-
- pending.forEach(callback => act(() => callback(now)))
- },
- /** Move the clock without running rAF — what a hidden document does. */
- idleUntil(now: number) {
- clock = now
- }
- }
-}
-
-const mount = reactRoot()
-const path = () => mount.container!.querySelector('path')!.getAttribute('d')
-
-/** jsdom has no layout, so `getBoundingClientRect` is 0×0 everywhere — which
- * would trip the loader's zero-size pause gate and freeze every frame. */
-const rect = { bottom: 40, height: 40, left: 0, right: 40, top: 0, width: 40, x: 0, y: 0 } as DOMRect
-
-function hide() {
- setDocumentHidden(true)
- document.dispatchEvent(new Event('visibilitychange'))
-}
-
-function show() {
- setDocumentHidden(false)
- document.dispatchEvent(new Event('visibilitychange'))
-}
-
-beforeEach(() => {
- // Fixed phase offset, so two mounts of the same curve are comparable.
- vi.spyOn(Math, 'random').mockReturnValue(0.5)
- vi.spyOn(Element.prototype, 'getBoundingClientRect').mockReturnValue(rect)
-})
-
-afterEach(() => {
- mount.unmount()
- vi.restoreAllMocks()
- vi.unstubAllGlobals()
- setDocumentHidden(false)
- document.documentElement.removeAttribute(PAUSED_ATTRIBUTE)
-})
-
-describe('Loader paused-time accounting', () => {
- it('freezes progress across a hidden interval where rAF never ran', () => {
- const clock = installFrameClock()
-
- mount.render(<Loader />)
- clock.frame(1_016)
- const beforeHide = path()
-
- hide()
- // A hidden document gets no rAF callbacks at all: the clock runs, the
- // animation does not.
- clock.idleUntil(61_000)
- show()
- clock.frame(61_000)
-
- expect(path()).toBe(beforeHide)
- })
-
- it('freezes progress when rAF is throttled rather than stopped while hidden', () => {
- const clock = installFrameClock()
-
- mount.render(<Loader />)
- clock.frame(1_016)
- const beforeHide = path()
-
- hide()
- // Chromium's throttled case: a callback every ~20 s over the same minute.
- clock.frame(20_000)
- clock.frame(40_000)
- clock.frame(60_000)
- show()
- clock.frame(61_016)
-
- expect(path()).toBe(beforeHide)
- })
-
- it('measures a renderer-paused stretch by the clock, not 16 ms per callback', () => {
- const clock = installFrameClock()
-
- // Reference: the curve as it looks at animation time 0.
- mount.render(<Loader />)
- const neverPaused = path()
-
- mount.unmount()
- document.documentElement.setAttribute(PAUSED_ATTRIBUTE, '')
-
- // 2.5 s of paused frames at a 25 ms cadence — a 120 Hz panel or a loaded
- // main thread deliver 16 ms frames no more often than any other cadence.
- mount.render(<Loader />)
-
- for (let now = 1_025; now <= 3_500; now += 25) {
- clock.frame(now)
- }
-
- // Paused frames still write nothing: the DOM keeps the curve from the last
- // frame that ran, so the mount frame left no path at all.
- expect(path()).toBeNull()
-
- document.documentElement.removeAttribute(PAUSED_ATTRIBUTE)
- clock.frame(3_525)
-
- expect(path()).toBe(neverPaused)
- })
-})
diff --git a/apps/desktop/src/components/ui/loader.tsx b/apps/desktop/src/components/ui/loader.tsx
index 265ca6be4dc..985a50cf596 100644
--- a/apps/desktop/src/components/ui/loader.tsx
+++ b/apps/desktop/src/components/ui/loader.tsx
@@ -328,83 +328,15 @@ export function Loader({
const groupRef = useRef<SVGGElement | null>(null)
const particleRefs = useRef<Array<SVGCircleElement | null>>([])
const pathRef = useRef<SVGPathElement | null>(null)
- const svgRef = useRef<SVGSVGElement | null>(null)
useEffect(() => {
let animationFrame = 0
- let pausedAt: number | null = null
- let pausedTotal = 0
const startedAt = performance.now()
const phaseOffset = Math.random()
particleRefs.current.length = config.particleCount
- const shouldPause = () => {
- // Pause when the document is hidden, the global renderer-pause flag is
- // set, or the host prefers reduced motion — same gates the compositor
- // animations in styles.css use. Also pause when the SVG is off-screen /
- // content-visibility skips it (intersection check is free inside rAF).
- if (typeof document !== 'undefined') {
- if (document.hidden) {
- return true
- }
-
- if (document.documentElement?.hasAttribute('data-renderer-animations-paused')) {
- return true
- }
-
- if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) {
- return true
- }
- }
-
- const svg = svgRef.current
-
- if (svg) {
- const rect = svg.getBoundingClientRect()
-
- // Zero-size means hidden by keep-alive tab (visibility:hidden but still
- // in DOM) or content-visibility skip — don't burn 60 fps updating it.
- if (rect.width === 0 && rect.height === 0) {
- return true
- }
- }
-
- return false
- }
-
- // rAF does not fire while the document is hidden, so the pause branch in
- // `render` never sees that interval — take the timestamp from the event
- // that announces it instead.
- const onVisibilityChange = () => {
- if (document.hidden && pausedAt === null) {
- pausedAt = performance.now()
- }
- }
-
- document.addEventListener('visibilitychange', onVisibilityChange)
-
const render = (now: number) => {
- if (shouldPause()) {
- // Freeze the animation clock at the timestamp the pause started.
- // rAF is throttled or stopped outright while paused, so charging one
- // assumed frame per callback under-counts a long pause by orders of
- // magnitude and the loader jumps forward on resume.
- if (pausedAt === null) {
- pausedAt = now
- }
-
- animationFrame = window.requestAnimationFrame(render)
-
- return
- }
-
- if (pausedAt !== null) {
- // Charge the measured pause, once, on the frame that resumes.
- pausedTotal += now - pausedAt
- pausedAt = null
- }
-
- const time = now - startedAt - pausedTotal
+ const time = now - startedAt
const progress = ((time + phaseOffset * config.durationMs) % config.durationMs) / config.durationMs
const detailScale = detailScaleFor(time, config, phaseOffset)
const rotation = rotationFor(time, config, phaseOffset)
@@ -429,10 +361,7 @@ export function Loader({
render(performance.now())
- return () => {
- document.removeEventListener('visibilitychange', onVisibilityChange)
- window.cancelAnimationFrame(animationFrame)
- }
+ return () => window.cancelAnimationFrame(animationFrame)
}, [config, pathSteps, strokeScale])
return (
@@ -442,13 +371,7 @@ export function Loader({
className={cn('inline-grid size-10 place-items-center text-primary', className)}
role={role}
>
- <svg
- aria-hidden="true"
- className="size-full overflow-visible"
- fill="none"
- ref={svgRef}
- viewBox="0 0 100 100"
- >
+ <svg aria-hidden="true" className="size-full overflow-visible" fill="none" viewBox="0 0 100 100">
<g ref={groupRef}>
<path
opacity="0.1"
diff --git a/apps/desktop/src/lib/raf-coalesce.ts b/apps/desktop/src/lib/raf-coalesce.ts
index 788b99d6e83..1ef42a3ef84 100644
--- a/apps/desktop/src/lib/raf-coalesce.ts
+++ b/apps/desktop/src/lib/raf-coalesce.ts
@@ -1,9 +1,10 @@
/** Coalesce a stream of values (pointermove positions, resize deltas) to one
* `apply` per animation frame, so a drag can't drive several layouts per frame.
* `push` records the latest value and schedules a frame; `finish` commits the
- * last value and cancels any pending frame (call it on pointerup/cancel).
+ * last value and cancels any pending frame (call it on pointerup/cancel);
+ * `cancel` drops the pending value without applying it (unmount teardown).
* `null` is the empty sentinel, so `T` must never legitimately be `null`. */
-export function rafCoalesce<T>(apply: (value: T) => void): { finish: () => void; push: (value: T) => void } {
+export function rafCoalesce<T>(apply: (value: T) => void): { cancel: () => void; finish: () => void; push: (value: T) => void } {
let frame: null | number = null
let pending: null | T = null
@@ -16,6 +17,14 @@ export function rafCoalesce<T>(apply: (value: T) => void): { finish: () => void;
}
return {
+ cancel() {
+ if (frame !== null) {
+ cancelAnimationFrame(frame)
+ frame = null
+ }
+
+ pending = null
+ },
finish() {
if (frame !== null) {
cancelAnimationFrame(frame)
diff --git a/apps/desktop/src/styles.css b/apps/desktop/src/styles.css
index f5480e90b3c..21208ec9d2f 100644
--- a/apps/desktop/src/styles.css
+++ b/apps/desktop/src/styles.css
@@ -45,7 +45,8 @@
.pet-wobble,
.progress-slide,
.kanban-arc,
- .glyph-spinner__strip
+ .glyph-spinner__strip,
+ .decode-cursor-blink
),
:root[data-renderer-animations-paused] .arc-border::before,
:root[data-renderer-animations-paused]
@@ -1240,16 +1241,8 @@
}
}
-/* ── #99889: per-instance @keyframes → static stylesheet ────────────────
- Each of these was previously rendered as a per-instance <style> tag inside
- its component (DecodeText, pane-shell LayoutTreeRoot, Starmap Timeline,
- onboarding Glyph). Inserting/removing a <style> that defines an
- `@keyframes` rule invalidates every animating element in the document
- (StyleRecalcInvalidation reason "@keyframes rule change" = 2,651 events in
- the 60 s trace). Moving them here makes the registry change once at load.
- The same bug family as #72844/#91473 and #91383; the per-instance form is
- also what multiplied decode-cursor duplicates in the live DOM on every
- Sessions/Bots tab switch. — fix #99889 */
+/* Keyframes live here, not in per-instance <style> tags: inserting or removing an
+ @keyframes rule invalidates every animating element in the document (#99889). */
@keyframes decode-cursor {
0%,
49% {
@@ -1263,19 +1256,7 @@
.decode-cursor-blink {
animation: decode-cursor 1s step-end infinite;
}
-@keyframes ob-decode-cursor {
- 0%,
- 49% {
- opacity: 1;
- }
- 50%,
- 100% {
- opacity: 0;
- }
-}
-.ob-decode-cursor-blink {
- animation: ob-decode-cursor 1s step-end infinite;
-}
+/* 0.001 start mirrors ZonesOverlay::GetAnimationAlpha's clamp(t / 200ms, 0.001, 1). */
@keyframes hermes-zone-fade {
from {
opacity: 0.001;
@@ -1294,17 +1275,6 @@
}
}
-@media (prefers-reduced-motion: reduce) {
- .decode-cursor-blink,
- .ob-decode-cursor-blink {
- animation: none !important;
- }
-}
-:root[data-renderer-animations-paused] .decode-cursor-blink,
-:root[data-renderer-animations-paused] .ob-decode-cursor-blink {
- animation-play-state: paused !important;
-}
-
/* No focus rings, anywhere. Kills the native outline plus Tailwind's
`focus-visible:ring-*` (a box-shadow driven by --tw-ring-*). Unlayered so it
beats the utilities layer without !important on the outline. The composer /