Skip to content

The agent that grows with you

perf(desktop): static keyframes, coalesced composer measures, clock-based loader pause

finn7633c60e7db671e
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 644f0a30367..972e1f814b2 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
@@ -114,8 +114,16 @@ export function useComposerMetrics({
// would re-register the observation.
const poppedOutRef = useRef(poppedOut)
poppedOutRef.current = poppedOut
-
- const syncComposerMetrics = useCallback(() => {
+ // #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 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.
@@ -180,8 +188,30 @@ export function useComposerMetrics({
}
}, [composerDockRef, composerRef, composerSurfaceRef, editorRef])
+ const syncComposerMetrics = useCallback(() => {
+ if (rafIdRef.current !== null) {
+ return
+ }
+
+ rafIdRef.current = window.requestAnimationFrame(() => {
+ rafIdRef.current = null
+ doSyncComposerMetrics()
+ })
+ }, [doSyncComposerMetrics])
+
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
diff --git a/apps/desktop/src/app/starmap/timeline.tsx b/apps/desktop/src/app/starmap/timeline.tsx
index 23056861a40..dd70b32d3d2 100644
--- a/apps/desktop/src/app/starmap/timeline.tsx
+++ b/apps/desktop/src/app/starmap/timeline.tsx
@@ -182,7 +182,6 @@ export const Timeline = memo(function Timeline({
return (
<div className="pointer-events-auto flex w-[28rem] max-w-full items-center gap-3 [-webkit-app-region:no-drag]">
- <style>{'@keyframes starmap-twinkle{0%,100%{opacity:var(--o,1)}50%{opacity:calc(var(--o,1) * 0.35)}}'}</style>
<button
aria-label={playing ? 'Pause' : 'Play timeline'}
diff --git a/apps/desktop/src/components/onboarding/glyph.tsx b/apps/desktop/src/components/onboarding/glyph.tsx
index a3166ec0d63..ecee40730dc 100644
--- a/apps/desktop/src/components/onboarding/glyph.tsx
+++ b/apps/desktop/src/components/onboarding/glyph.tsx
@@ -127,10 +127,8 @@ 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"
- style={{ animation: 'ob-decode-cursor 1s step-end infinite' }}
+ 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"
/>
- <style>{'@keyframes ob-decode-cursor { 0%, 49% { opacity: 1 } 50%, 100% { opacity: 0 } }'}</style>
</span>
)
}
diff --git a/apps/desktop/src/components/pane-shell/tree/renderer/index.tsx b/apps/desktop/src/components/pane-shell/tree/renderer/index.tsx
index b4f3f7b1a8e..d2f59868cf8 100644
--- a/apps/desktop/src/components/pane-shell/tree/renderer/index.tsx
+++ b/apps/desktop/src/components/pane-shell/tree/renderer/index.tsx
@@ -52,8 +52,6 @@ export function LayoutTreeRoot({ children, titlebar = false }: { children?: Reac
return (
<div className="relative flex min-h-0 min-w-0 flex-1">
- {/* ZonesOverlay::GetAnimationAlpha ramp: clamp(t / 200ms, 0.001, 1). */}
- <style>{`@keyframes hermes-zone-fade { from { opacity: 0.001 } to { opacity: 1 } }`}</style>
{/* THE SEAM INVARIANT: boundaries are drawn by the tree (one sash
hairline per seam) — content mounted in a zone must not paint its
own edge chrome. App components (asides, the shadcn sidebar) carry
diff --git a/apps/desktop/src/components/ui/decode-text.tsx b/apps/desktop/src/components/ui/decode-text.tsx
index edd91641a66..ac9be7d667b 100644
--- a/apps/desktop/src/components/ui/decode-text.tsx
+++ b/apps/desktop/src/components/ui/decode-text.tsx
@@ -108,14 +108,12 @@ export function DecodeText({
)}
{...props}
>
- {cursor && <style>{'@keyframes decode-cursor { 0%, 49% { opacity: 1 } 50%, 100% { opacity: 0 } }'}</style>}
{staticPrefix}
{tail}
{cursor && (
<span
aria-hidden="true"
- className="dither ml-0.5 inline-block size-2 shrink-0 -translate-y-px rounded-[1px]"
- style={{ animation: 'decode-cursor 1s step-end infinite' }}
+ className="dither ml-0.5 inline-block size-2 shrink-0 -translate-y-px rounded-[1px] decode-cursor-blink"
/>
)}
</span>
diff --git a/apps/desktop/src/components/ui/loader.test.tsx b/apps/desktop/src/components/ui/loader.test.tsx
new file mode 100644
index 00000000000..500e87241fa
--- /dev/null
+++ b/apps/desktop/src/components/ui/loader.test.tsx
@@ -0,0 +1,146 @@
+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 985a50cf596..265ca6be4dc 100644
--- a/apps/desktop/src/components/ui/loader.tsx
+++ b/apps/desktop/src/components/ui/loader.tsx
@@ -328,15 +328,83 @@ 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) => {
- const time = now - startedAt
+ 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 progress = ((time + phaseOffset * config.durationMs) % config.durationMs) / config.durationMs
const detailScale = detailScaleFor(time, config, phaseOffset)
const rotation = rotationFor(time, config, phaseOffset)
@@ -361,7 +429,10 @@ export function Loader({
render(performance.now())
- return () => window.cancelAnimationFrame(animationFrame)
+ return () => {
+ document.removeEventListener('visibilitychange', onVisibilityChange)
+ window.cancelAnimationFrame(animationFrame)
+ }
}, [config, pathSteps, strokeScale])
return (
@@ -371,7 +442,13 @@ 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" viewBox="0 0 100 100">
+ <svg
+ aria-hidden="true"
+ className="size-full overflow-visible"
+ fill="none"
+ ref={svgRef}
+ viewBox="0 0 100 100"
+ >
<g ref={groupRef}>
<path
opacity="0.1"
diff --git a/apps/desktop/src/styles.css b/apps/desktop/src/styles.css
index 24493d1b07c..f5480e90b3c 100644
--- a/apps/desktop/src/styles.css
+++ b/apps/desktop/src/styles.css
@@ -1240,6 +1240,71 @@
}
}
+/* ── #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 decode-cursor {
+ 0%,
+ 49% {
+ opacity: 1;
+ }
+ 50%,
+ 100% {
+ opacity: 0;
+ }
+}
+.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;
+}
+@keyframes hermes-zone-fade {
+ from {
+ opacity: 0.001;
+ }
+ to {
+ opacity: 1;
+ }
+}
+@keyframes starmap-twinkle {
+ 0%,
+ 100% {
+ opacity: var(--o, 1);
+ }
+ 50% {
+ opacity: calc(var(--o, 1) * 0.35);
+ }
+}
+
+@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 /