Skip to content

The agent that grows with you

perf(desktop): compositor-only glyph spinner (no per-tick DOM mutation)

Royalaidb484933005ba
diff --git a/apps/desktop/src/components/ui/glyph-spinner.css b/apps/desktop/src/components/ui/glyph-spinner.css
new file mode 100644
index 00000000000..825c54ffdc8
--- /dev/null
+++ b/apps/desktop/src/components/ui/glyph-spinner.css
@@ -0,0 +1,61 @@
+/* Compositor-only glyph spinner.
+ *
+ * The previous implementation ticked a setInterval and replaced
+ * `glyph.textContent` every frame. Replacing a text node is a structural DOM
+ * mutation, so each tick scheduled a style recalculation — and because these
+ * spinners sit inside the transcript, that recalc resolved against the whole
+ * document. Scheduler attribution on the incident trace put 133 of 138 wide
+ * document-scale recalcs on this ticker (0 of 254 cheap ones), which is the
+ * incident.
+ *
+ * Every frame is now in the DOM from mount as a vertical strip, and a
+ * `transform: translateY` keyframes animation scrolls it one frame at a time.
+ * Transform animations run on the compositor: no JS timer, no text mutation,
+ * no style recalc, no layout, nothing scheduled per frame.
+ *
+ * The strip is N frames tall and each frame is exactly 1em, so translating by
+ * -100% travels exactly N frames. `steps(N)` (jump-end) samples that travel at
+ * 0, 1/N, ... (N-1)/N, i.e. it parks on frame 0..N-1 for one interval each and
+ * then wraps — the same sequence and cadence the ticker produced. Both N and
+ * the duration arrive as custom properties set inline per spinner, so all 18
+ * spinner variants (16 distinct frame/interval shapes) share this one rule set
+ * with no generated or colliding per-variant keyframes.
+ */
+
+.glyph-spinner {
+ display: block;
+ height: 1em;
+ overflow: hidden;
+ line-height: 1;
+}
+
+.glyph-spinner__strip {
+ display: block;
+ animation: glyph-spinner-advance var(--glyph-spinner-duration) steps(var(--glyph-spinner-frames)) infinite;
+}
+
+.glyph-spinner__frame {
+ display: block;
+ height: 1em;
+ line-height: 1;
+}
+
+/* Kept-alive pane that is currently an inactive tab. Hidden panes normally get
+ `content-visibility: hidden`, which already stops animations in the skipped
+ subtree, but that containment has a runtime kill switch and older pane layers
+ only set `visibility: hidden` — which does NOT stop an animation. This keeps
+ the original explicit guarantee ("N mounted tabs each ticking burns CPU for
+ pixels nobody can see") independent of which of those is in play. */
+.glyph-spinner[data-paused='true'] .glyph-spinner__strip {
+ animation-play-state: paused;
+}
+
+@keyframes glyph-spinner-advance {
+ from {
+ transform: translateY(0);
+ }
+
+ to {
+ transform: translateY(-100%);
+ }
+}
diff --git a/apps/desktop/src/components/ui/glyph-spinner.test.tsx b/apps/desktop/src/components/ui/glyph-spinner.test.tsx
index 686ee91da15..1206c163f9c 100644
--- a/apps/desktop/src/components/ui/glyph-spinner.test.tsx
+++ b/apps/desktop/src/components/ui/glyph-spinner.test.tsx
@@ -1,15 +1,52 @@
-import { act, render, screen } from '@testing-library/react'
+// GlyphSpinner animates on the compositor: every frame is in the DOM from
+// mount and a transform keyframes animation scrolls between them. It has no
+// timer and performs no per-frame DOM write, because the setInterval +
+// `glyph.textContent` ticker this replaced was scheduling a document-scale
+// style recalculation on every tick (133 of 138 wide recalcs on the incident
+// trace).
+//
+// These tests therefore pin the DATA and WIRING that make the CSS correct,
+// which is all jsdom can see — it has no animation engine, so the motion
+// itself is not observable here:
+//
+// - the strip carries every frame, in order, so `steps(N)` lands on each one;
+// - the custom properties feeding `steps()` / duration match the source data,
+// so cadence per variant is preserved;
+// - no timer is ever created (the ticker is really gone);
+// - the kept-alive-tab gate still resolves to a paused animation;
+// - the strip is named in the global renderer-pause rule, which is what now
+// delivers the window-blur / minimize / document-hidden suspension that
+// this component used to implement itself via
+// createRendererLoopPauseController. That mechanism has its own coverage in
+// lib/renderer-loop-pause.test.ts.
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+
+import { render, screen } from '@testing-library/react'
import { Profiler, type ProfilerOnRenderCallback } from 'react'
+import spinners from 'unicode-animations'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { PaneVisibleContext } from '@/components/pane-shell/pane-visibility'
import { GlyphSpinner } from './glyph-spinner'
+const BRAILLE = spinners.braille
+
+function strip(): HTMLElement {
+ const status = screen.getByRole('status', { name: 'Loading' })
+ const found = status.querySelector<HTMLElement>('.glyph-spinner__strip')
+
+ if (!found) {
+ throw new Error('no frame strip rendered')
+ }
+
+ return found
+}
+
describe('GlyphSpinner', () => {
beforeEach(() => {
vi.useFakeTimers()
- vi.spyOn(globalThis.document, 'hasFocus').mockReturnValue(true)
})
afterEach(() => {
@@ -18,7 +55,41 @@ describe('GlyphSpinner', () => {
vi.useRealTimers()
})
- it('advances its glyph without an update-phase React commit', () => {
+ it('renders every frame in source order as the scroll strip', () => {
+ render(<GlyphSpinner spinner="braille" />)
+
+ const frames = [...strip().querySelectorAll('.glyph-spinner__frame')].map(node => node.textContent)
+
+ expect(frames).toEqual([...BRAILLE.frames])
+ // The old ticker started on frame 0; steps() starts the strip there too.
+ expect(frames[0]).toBe('⠋')
+ })
+
+ it('feeds steps() and the duration from the spinner data, so cadence is unchanged', () => {
+ render(<GlyphSpinner spinner="braille" />)
+
+ const style = strip().style
+
+ // One full cycle is frames x interval; steps(frames) parks on each frame
+ // for exactly `interval` ms, which is what the setInterval did.
+ expect(style.getPropertyValue('--glyph-spinner-frames')).toBe(String(BRAILLE.frames.length))
+ expect(style.getPropertyValue('--glyph-spinner-duration')).toBe(`${BRAILLE.frames.length * BRAILLE.interval}ms`)
+ })
+
+ it('keeps per-variant cadence distinct', () => {
+ render(<GlyphSpinner ariaLabel="Working" spinner="breathe" />)
+
+ const node = screen.getByRole('status', { name: 'Working' })
+ const found = node.querySelector<HTMLElement>('.glyph-spinner__strip')!
+ const breathe = spinners.breathe
+
+ expect(found.querySelectorAll('.glyph-spinner__frame')).toHaveLength(breathe.frames.length)
+ expect(found.style.getPropertyValue('--glyph-spinner-duration')).toBe(
+ `${breathe.frames.length * breathe.interval}ms`
+ )
+ })
+
+ it('creates no timer and no update-phase React commit', () => {
let updateCommits = 0
const onRender: ProfilerOnRenderCallback = (_id, phase) => {
@@ -33,135 +104,53 @@ describe('GlyphSpinner', () => {
</Profiler>
)
- const status = screen.getByRole('status', { name: 'Loading' })
- expect(status.textContent).toBe('⠋')
+ // The whole point: the ticker is gone, so nothing is scheduled at all.
+ expect(vi.getTimerCount()).toBe(0)
- act(() => vi.advanceTimersByTime(80))
+ vi.advanceTimersByTime(5_000)
- expect(status.textContent).toBe('⠙')
+ expect(vi.getTimerCount()).toBe(0)
expect(updateCommits).toBe(0)
})
- it('does not tick while its kept-alive pane is hidden', () => {
+ it('pauses while its kept-alive pane is hidden, and resumes when shown', () => {
const { rerender } = render(
<PaneVisibleContext.Provider value={false}>
<GlyphSpinner spinner="braille" />
</PaneVisibleContext.Provider>
)
- const status = screen.getByRole('status', { name: 'Loading' })
+ const viewport = () => screen.getByRole('status', { name: 'Loading' }).querySelector('.glyph-spinner')
- expect(status.textContent).toBe('⠋')
- expect(vi.getTimerCount()).toBe(0)
+ expect(viewport()?.getAttribute('data-paused')).toBe('true')
rerender(
<PaneVisibleContext.Provider value>
<GlyphSpinner spinner="braille" />
</PaneVisibleContext.Provider>
)
- expect(vi.getTimerCount()).toBe(1)
-
- act(() => vi.advanceTimersByTime(80))
- expect(status.textContent).toBe('⠙')
-
- rerender(
- <PaneVisibleContext.Provider value={false}>
- <GlyphSpinner spinner="braille" />
- </PaneVisibleContext.Provider>
- )
- expect(vi.getTimerCount()).toBe(0)
- const frozen = status.textContent
- act(() => vi.advanceTimersByTime(800))
- expect(status.textContent).toBe(frozen)
+ expect(viewport()?.hasAttribute('data-paused')).toBe(false)
})
- it('suspends animation while the Desktop window is inactive', () => {
+ it('hides the decorative frames from assistive tech', () => {
render(<GlyphSpinner spinner="braille" />)
+ // role="status" is a live region. The frames must not be announced — the
+ // old implementation rewrote this region's text ~12x/second.
const status = screen.getByRole('status', { name: 'Loading' })
- expect(vi.getTimerCount()).toBe(1)
-
- act(() => window.dispatchEvent(new Event('blur')))
- expect(vi.getTimerCount()).toBe(0)
- const frozen = status.textContent
- act(() => vi.advanceTimersByTime(800))
- expect(status.textContent).toBe(frozen)
-
- act(() => window.dispatchEvent(new Event('focus')))
- expect(vi.getTimerCount()).toBe(1)
-
- act(() => vi.advanceTimersByTime(80))
- expect(status.textContent).not.toBe(frozen)
+ expect(status.querySelector('.glyph-spinner')?.getAttribute('aria-hidden')).toBe('true')
})
- it('suspends animation while the Electron window is minimized or hidden, then resumes on restore', () => {
- let windowStateCallback: ((payload: { isMinimized?: boolean; isVisible?: boolean }) => void) | null = null
-
- Object.defineProperty(window, 'hermesDesktop', {
- configurable: true,
- value: {
- onWindowStateChanged: vi.fn((callback: typeof windowStateCallback) => {
- windowStateCallback = callback
-
- return () => {
- if (windowStateCallback === callback) {
- windowStateCallback = null
- }
- }
- })
- }
- })
-
- try {
- render(<GlyphSpinner spinner="braille" />)
-
- const status = screen.getByRole('status', { name: 'Loading' })
- expect(windowStateCallback).not.toBeNull()
- expect(vi.getTimerCount()).toBe(1)
-
- act(() => windowStateCallback?.({ isMinimized: true, isVisible: false }))
- expect(vi.getTimerCount()).toBe(0)
-
- const frozen = status.textContent
- act(() => vi.advanceTimersByTime(800))
- expect(status.textContent).toBe(frozen)
+ it('is wired into the global renderer-animation pause rule', () => {
+ // Window blur / minimize / document-hidden suspension now comes from this
+ // rule rather than from a per-spinner pause controller. Dropping the class
+ // from it would silently leave every spinner animating behind an inactive
+ // window — the CPU burn the original implementation existed to avoid.
+ const css = readFileSync(resolve(process.cwd(), 'src/styles.css'), 'utf8')
+ const pauseRule = css.slice(css.indexOf(':root[data-renderer-animations-paused]'))
- act(() => windowStateCallback?.({ isMinimized: false, isVisible: true }))
- expect(vi.getTimerCount()).toBe(1)
-
- act(() => vi.advanceTimersByTime(80))
- expect(status.textContent).not.toBe(frozen)
- } finally {
- delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop
- }
- })
-
- it('suspends animation while the document is hidden', () => {
- render(<GlyphSpinner spinner="braille" />)
-
- const status = screen.getByRole('status', { name: 'Loading' })
- expect(vi.getTimerCount()).toBe(1)
-
- Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' })
-
- try {
- act(() => document.dispatchEvent(new Event('visibilitychange')))
- expect(vi.getTimerCount()).toBe(0)
-
- const frozen = status.textContent
- act(() => vi.advanceTimersByTime(800))
- expect(status.textContent).toBe(frozen)
-
- Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' })
- act(() => document.dispatchEvent(new Event('visibilitychange')))
- expect(vi.getTimerCount()).toBe(1)
-
- act(() => vi.advanceTimersByTime(80))
- expect(status.textContent).not.toBe(frozen)
- } finally {
- Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' })
- }
+ expect(pauseRule.slice(0, pauseRule.indexOf('animation-play-state'))).toContain('.glyph-spinner__strip')
})
})
diff --git a/apps/desktop/src/components/ui/glyph-spinner.tsx b/apps/desktop/src/components/ui/glyph-spinner.tsx
index 1fc50bbe4b8..c5a331d542b 100644
--- a/apps/desktop/src/components/ui/glyph-spinner.tsx
+++ b/apps/desktop/src/components/ui/glyph-spinner.tsx
@@ -1,8 +1,9 @@
-import { useEffect, useRef } from 'react'
+import './glyph-spinner.css'
+
+import type { CSSProperties } from 'react'
import spinners, { type BrailleSpinnerName as SpinnerName } from 'unicode-animations'
import { usePaneVisible } from '@/components/pane-shell/pane-visibility'
-import { createRendererLoopPauseController } from '@/lib/renderer-loop-pause'
import { cn } from '@/lib/utils'
export type { SpinnerName }
@@ -41,69 +42,54 @@ interface GlyphSpinnerProps {
* the desktop and terminal experiences read the same visually. Renders inside
* an `inline-flex` cell with `leading-none` and `items-center` so it sits
* vertically centred inside its parent's line-box.
+ *
+ * Animated entirely on the compositor — every frame is in the DOM from mount
+ * and a transform keyframes animation scrolls between them. There is no timer
+ * and no per-frame DOM write, because the ticker this replaced was scheduling
+ * document-scale style recalculation on every tick (see glyph-spinner.css).
+ *
+ * The outer cell keeps the exact classes it always had, so consumer sizing
+ * (`size-3`, `text-[0.75rem]`, colour, opacity) lands unchanged; the 1em-tall
+ * clipping viewport is centred inside it by the same `items-center` that used
+ * to centre the single glyph.
*/
export function GlyphSpinner({ ariaLabel = 'Loading', className, spinner = 'braille' }: GlyphSpinnerProps) {
const spin = FRAMES_BY_NAME[spinner] ?? FRAMES_BY_NAME.braille!
- const glyphRef = useRef<HTMLSpanElement>(null)
// Pause when this surface is a hidden (kept-alive) tab: N mounted tabs each
- // ticking a setInterval burns CPU for pixels nobody can see.
+ // animating burns CPU for pixels nobody can see. Window blur / minimize /
+ // document-hidden are handled globally instead, by the
+ // `:root[data-renderer-animations-paused]` rule in styles.css that
+ // main.tsx's installRendererAnimationPauseState() drives — the same
+ // mechanism every other continuous decorative animation already uses.
const visible = usePaneVisible()
- useEffect(() => {
- const glyph = glyphRef.current
-
- if (!visible || !glyph) {
- return
- }
-
- let frame = 0
- let timer: number | undefined
- let pauseController: ReturnType<typeof createRendererLoopPauseController> | undefined
- glyph.textContent = spin.frames[frame]
-
- const stopAnimation = () => {
- if (timer === undefined) {
- return
- }
-
- window.clearInterval(timer)
- timer = undefined
- }
-
- const syncAnimation = () => {
- if (pauseController?.isPaused()) {
- stopAnimation()
-
- return
- }
-
- if (timer !== undefined) {
- return
- }
-
- timer = window.setInterval(() => {
- frame = (frame + 1) % spin.frames.length
- glyph.textContent = spin.frames[frame]
- }, spin.interval)
- }
-
- pauseController = createRendererLoopPauseController(syncAnimation)
- syncAnimation()
-
- return () => {
- pauseController.dispose()
- stopAnimation()
- }
- }, [spin, visible])
-
return (
<span
aria-label={ariaLabel}
className={cn('inline-flex items-center justify-center font-mono leading-none tabular-nums', className)}
- ref={glyphRef}
role="status"
>
- {spin.frames[0]}
+ {/* Hidden from assistive tech: the accessible name is the label above.
+ The frames are decorative, and this is a live region — the old
+ implementation rewrote its text ~12x/second, which would announce a
+ new glyph on every tick. */}
+ <span aria-hidden="true" className="glyph-spinner" data-paused={visible ? undefined : 'true'}>
+ <span
+ className="glyph-spinner__strip"
+ style={
+ {
+ '--glyph-spinner-duration': `${spin.frames.length * spin.interval}ms`,
+ '--glyph-spinner-frames': spin.frames.length
+ } as CSSProperties
+ }
+ >
+ {spin.frames.map((frame, index) => (
+ <span className="glyph-spinner__frame" key={`${index}:${frame}`}>
+ {frame}
+ </span>
+ ))}
+ </span>
+ </span>
</span>
)
}
diff --git a/apps/desktop/src/styles.css b/apps/desktop/src/styles.css
index 041c9a69c0d..396ed175d9d 100644
--- a/apps/desktop/src/styles.css
+++ b/apps/desktop/src/styles.css
@@ -32,7 +32,17 @@
behind another app. main.tsx owns this attribute only for the primary
window; wake/pet overlays retain their purpose-built visibility behavior. */
:root[data-renderer-animations-paused]
- :is(.shimmer, .quest-glow, .pet-egg, .pet-egg__glow, .pet-egg-shadow, .pet-wobble, .progress-slide, .kanban-arc),
+ :is(
+ .shimmer,
+ .quest-glow,
+ .pet-egg,
+ .pet-egg__glow,
+ .pet-egg-shadow,
+ .pet-wobble,
+ .progress-slide,
+ .kanban-arc,
+ .glyph-spinner__strip
+ ),
:root[data-renderer-animations-paused] .arc-border::before,
:root[data-renderer-animations-paused]
[data-slot='aui_assistant-message-content']