Skip to content

The agent that grows with you

feat(desktop): shared createBudgetedLoop helper for decorative rAF animations

Tekniumd109785bb3ca
diff --git a/apps/desktop/src/components/chat/image-generation-placeholder.tsx b/apps/desktop/src/components/chat/image-generation-placeholder.tsx
index f693376b002..9244bbe6ec5 100644
--- a/apps/desktop/src/components/chat/image-generation-placeholder.tsx
+++ b/apps/desktop/src/components/chat/image-generation-placeholder.tsx
@@ -2,7 +2,7 @@ import { type FC, useCallback, useEffect, useRef } from 'react'
import { useResizeObserver } from '@/hooks/use-resize-observer'
import { onThemeRepaint } from '@/hooks/use-theme-epoch'
-import { createRendererLoopPauseController } from '@/lib/renderer-loop-pause'
+import { createBudgetedLoop } from '@/lib/budgeted-loop'
type Rgb = { r: number; g: number; b: number }
@@ -256,10 +256,6 @@ const drawAsciiDiffusion = (
const MAX_ANIMATED_INSTANCES = 2
let activeAnimatedCount = 0
-// ~15fps paint target for the animated shimmer — visually equivalent at
-// placeholder scale, 4x fewer full-canvas redraws than display cadence.
-const FRAME_INTERVAL = 1000 / 15
-
export const DiffusionCanvas: FC = () => {
const canvasRef = useRef<HTMLCanvasElement | null>(null)
const sizeRef = useRef({ width: 0, height: 0 })
@@ -311,7 +307,7 @@ export const DiffusionCanvas: FC = () => {
sizeRef.current = fitCanvas(canvas, ctx)
- // Over the concurrent cap — draw one static frame, skip the rAF loop so
+ // Over the concurrent cap — draw one static frame, skip the loop so
// extra instances are zero-cost (#79077). Each animated instance redraws
// its full canvas per frame, so N instances multiply cost linearly.
if (activeAnimatedCount >= MAX_ANIMATED_INSTANCES) {
@@ -323,57 +319,20 @@ export const DiffusionCanvas: FC = () => {
activeAnimatedCount++
- let frame = 0
- let lastDraw = 0
- let stopped = false
- let pauseController: ReturnType<typeof createRendererLoopPauseController> | null = null
-
- const cancelFrame = () => {
- if (frame !== 0) {
- window.cancelAnimationFrame(frame)
- frame = 0
- }
- }
-
- const scheduleFrame = () => {
- if (stopped || pauseController?.isPaused() || frame !== 0) {
- return
- }
-
- frame = window.requestAnimationFrame(draw)
- }
-
- const draw = (now: number) => {
- frame = 0
-
- if (stopped || pauseController?.isPaused()) {
- return
- }
-
- // 15fps is visually equivalent for this placeholder shimmer and does
- // 4x fewer full-canvas redraws than display cadence (#79077).
- if (now - lastDraw >= FRAME_INTERVAL) {
+ // 15fps is visually equivalent for this placeholder shimmer and does 4x
+ // fewer full-canvas redraws than display cadence (#79077). The loop also
+ // pauses while the window is hidden/minimized/unfocused (#88396).
+ const loop = createBudgetedLoop(
+ now => {
const { width, height } = sizeRef.current
ctx.clearRect(0, 0, width, height)
drawAsciiDiffusion(ctx, themeRef.current, width, height, now / 1000)
- lastDraw = now
- }
-
- scheduleFrame()
- }
-
- const handleVisibilityChange = () => {
- cancelFrame()
- scheduleFrame()
- }
-
- pauseController = createRendererLoopPauseController(handleVisibilityChange)
- scheduleFrame()
+ },
+ { fps: 15 }
+ )
return () => {
- stopped = true
- cancelFrame()
- pauseController.dispose()
+ loop.dispose()
activeAnimatedCount--
}
}, [])
diff --git a/apps/desktop/src/lib/budgeted-loop.test.ts b/apps/desktop/src/lib/budgeted-loop.test.ts
new file mode 100644
index 00000000000..3741518c65c
--- /dev/null
+++ b/apps/desktop/src/lib/budgeted-loop.test.ts
@@ -0,0 +1,173 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { createBudgetedLoop } from './budgeted-loop'
+
+let windowStateCallback: ((payload: { isMinimized?: boolean; isVisible?: boolean }) => void) | null = null
+
+function installRaf() {
+ let nextId = 1
+ const frames = new Map<number, FrameRequestCallback>()
+
+ const request = vi.fn((callback: FrameRequestCallback) => {
+ const id = nextId++
+ frames.set(id, callback)
+
+ return id
+ })
+
+ const cancel = vi.fn((id: number) => {
+ frames.delete(id)
+ })
+
+ Object.defineProperty(window, 'requestAnimationFrame', { configurable: true, value: request })
+ Object.defineProperty(window, 'cancelAnimationFrame', { configurable: true, value: cancel })
+
+ return {
+ pending: () => frames.size,
+ runNext: (now: number) => {
+ const next = frames.entries().next().value
+
+ if (!next) {
+ throw new Error('No pending RAF')
+ }
+
+ const [id, callback] = next
+ frames.delete(id)
+ callback(now)
+ }
+ }
+}
+
+function installWindowStateBridge() {
+ windowStateCallback = null
+ Object.defineProperty(window, 'hermesDesktop', {
+ configurable: true,
+ value: {
+ onWindowStateChanged: vi.fn((callback: typeof windowStateCallback) => {
+ windowStateCallback = callback
+
+ return () => {
+ if (windowStateCallback === callback) {
+ windowStateCallback = null
+ }
+ }
+ })
+ }
+ })
+}
+
+describe('createBudgetedLoop', () => {
+ beforeEach(() => {
+ vi.spyOn(document, 'hasFocus').mockReturnValue(true)
+ installWindowStateBridge()
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop
+ })
+
+ it('enforces the fps budget: frames inside the interval reschedule without drawing', () => {
+ const raf = installRaf()
+ const draw = vi.fn()
+ const loop = createBudgetedLoop(draw, { fps: 15 })
+
+ expect(raf.pending()).toBe(1)
+
+ raf.runNext(1000)
+ expect(draw).toHaveBeenCalledTimes(1)
+
+ raf.runNext(1010) // inside the ~66.7ms budget
+ expect(draw).toHaveBeenCalledTimes(1)
+ expect(raf.pending()).toBe(1) // loop stays alive
+
+ raf.runNext(1080) // past the budget
+ expect(draw).toHaveBeenCalledTimes(2)
+
+ loop.dispose()
+ })
+
+ it('pauses while the window is not observable and resumes when it is', () => {
+ const raf = installRaf()
+ const draw = vi.fn()
+ const loop = createBudgetedLoop(draw)
+
+ expect(raf.pending()).toBe(1)
+
+ window.dispatchEvent(new Event('blur'))
+ expect(raf.pending()).toBe(0)
+
+ window.dispatchEvent(new Event('focus'))
+ expect(raf.pending()).toBe(1)
+
+ windowStateCallback?.({ isMinimized: true, isVisible: false })
+ expect(raf.pending()).toBe(0)
+
+ windowStateCallback?.({ isMinimized: false, isVisible: true })
+ expect(raf.pending()).toBe(1)
+
+ loop.dispose()
+ })
+
+ it('parks when idleWhen reports nothing to animate and wakes on demand', () => {
+ const raf = installRaf()
+ const draw = vi.fn()
+ let idle = false
+ const loop = createBudgetedLoop(draw, { fps: 15, idleWhen: () => idle })
+
+ raf.runNext(1000)
+ expect(raf.pending()).toBe(1) // busy -> keeps running
+
+ idle = true
+ raf.runNext(1100)
+ expect(raf.pending()).toBe(0) // parked, zero pending work
+ expect(loop.isDormant()).toBe(true)
+
+ loop.wake() // still idle — but wake schedules; next tick re-parks
+ expect(raf.pending()).toBe(1)
+ raf.runNext(1200)
+ expect(raf.pending()).toBe(0)
+
+ idle = false
+ loop.wake()
+ expect(raf.pending()).toBe(1)
+ raf.runNext(1300)
+ expect(loop.isDormant()).toBe(false)
+ expect(raf.pending()).toBe(1)
+
+ loop.dispose()
+ })
+
+ it('a parked loop does not resume from focus/visibility churn alone', () => {
+ const raf = installRaf()
+ let idle = true
+ const loop = createBudgetedLoop(vi.fn(), { idleWhen: () => idle })
+
+ raf.runNext(1000)
+ expect(raf.pending()).toBe(0)
+ expect(loop.isDormant()).toBe(true)
+
+ window.dispatchEvent(new Event('blur'))
+ window.dispatchEvent(new Event('focus'))
+ expect(raf.pending()).toBe(0) // dormancy survives observability churn
+
+ loop.dispose()
+ })
+
+ it('dispose cancels the pending frame and makes wake a no-op', () => {
+ const raf = installRaf()
+ const draw = vi.fn()
+ const loop = createBudgetedLoop(draw)
+
+ expect(raf.pending()).toBe(1)
+
+ loop.dispose()
+ expect(raf.pending()).toBe(0)
+
+ loop.wake()
+ window.dispatchEvent(new Event('focus'))
+ expect(raf.pending()).toBe(0)
+
+ loop.dispose() // idempotent
+ })
+})
diff --git a/apps/desktop/src/lib/budgeted-loop.ts b/apps/desktop/src/lib/budgeted-loop.ts
new file mode 100644
index 00000000000..2d2aff658ad
--- /dev/null
+++ b/apps/desktop/src/lib/budgeted-loop.ts
@@ -0,0 +1,140 @@
+/**
+ * Budgeted renderer loop — the one way to run a decorative rAF animation.
+ *
+ * Desktop has repeatedly shipped the same bug class: an animation loop that
+ * never sleeps (bots face clock #88543, pixel egg #88406, diffusion
+ * placeholder #88564, status pulse / spinner in the #77651 wave). Each fix
+ * re-implemented the same four behaviors by hand. This helper owns them:
+ *
+ * - **fps budget** — paints are skipped until `1000 / fps` elapsed; the loop
+ * still rides rAF so Chromium can align and pause it natively.
+ * - **observability pause** — wired to `createRendererLoopPauseController`:
+ * the loop cancels while the window is hidden, minimized, or unfocused and
+ * resumes when observable.
+ * - **idle dormancy** — when `idleWhen()` returns true after a draw, the loop
+ * parks (zero pending frames, zero timers) until `wake()` is called. This
+ * is the piece every hand-rolled loop forgot: "nothing visible to animate"
+ * must cost nothing.
+ * - **teardown** — `dispose()` cancels the frame, disposes the pause
+ * controller, and makes every later `wake()` a no-op. Callers MUST call it
+ * from their effect cleanup / plugin disposer.
+ *
+ * Usage:
+ *
+ * ```ts
+ * const loop = createBudgetedLoop(now => paint(now), {
+ * fps: 15,
+ * idleWhen: () => visibleThings.size === 0
+ * })
+ * // something became animatable again:
+ * loop.wake()
+ * // effect cleanup / plugin disable:
+ * loop.dispose()
+ * ```
+ */
+
+import { createRendererLoopPauseController } from '@/lib/renderer-loop-pause'
+
+export interface BudgetedLoopOptions {
+ /** Paint budget in frames per second. Default 15 — visually smooth for
+ * decorative/avatar-scale animation at a quarter of display cadence. */
+ fps?: number
+ /** Return true when there is nothing worth animating (no visible targets,
+ * animation finished). Checked after every draw; when true the loop parks
+ * until `wake()`. Omit for loops that should run whenever observable. */
+ idleWhen?: () => boolean
+ /** Forwarded to the pause controller. Default true (pause on blur). */
+ pauseWhenUnfocused?: boolean
+}
+
+export interface BudgetedLoop {
+ /** Cancel everything and detach listeners. Idempotent; wake() after this is
+ * a no-op. Call from effect cleanup or the plugin disposer. */
+ dispose: () => void
+ /** True while parked by `idleWhen` (diagnostics/tests). */
+ isDormant: () => boolean
+ /** Resume a loop parked by `idleWhen` (e.g. a target mounted or scrolled
+ * into view). Safe to call redundantly; no-op while running or disposed. */
+ wake: () => void
+}
+
+export function createBudgetedLoop(
+ draw: (now: number) => void,
+ { fps = 15, idleWhen, pauseWhenUnfocused = true }: BudgetedLoopOptions = {}
+): BudgetedLoop {
+ const frameInterval = 1000 / fps
+ let frame = 0
+ let lastDraw = -Infinity
+ let dormant = false
+ let disposed = false
+
+ const cancelFrame = () => {
+ if (frame !== 0) {
+ window.cancelAnimationFrame(frame)
+ frame = 0
+ }
+ }
+
+ const scheduleFrame = () => {
+ if (disposed || dormant || pauseController.isPaused() || frame !== 0) {
+ return
+ }
+
+ frame = window.requestAnimationFrame(tick)
+ }
+
+ const tick = (now: number) => {
+ frame = 0
+
+ if (disposed || pauseController.isPaused()) {
+ return
+ }
+
+ if (now - lastDraw >= frameInterval) {
+ draw(now)
+ lastDraw = now
+ }
+
+ // Idle dormancy: nothing to animate -> park with zero pending work.
+ // The owner wakes us when a target (re)appears.
+ if (idleWhen?.()) {
+ dormant = true
+
+ return
+ }
+
+ scheduleFrame()
+ }
+
+ const handlePauseChange = () => {
+ cancelFrame()
+ scheduleFrame()
+ }
+
+ const pauseController = createRendererLoopPauseController(handlePauseChange, { pauseWhenUnfocused })
+
+ const wake = () => {
+ if (disposed || !dormant) {
+ return
+ }
+
+ dormant = false
+ scheduleFrame()
+ }
+
+ scheduleFrame()
+
+ return {
+ dispose: () => {
+ if (disposed) {
+ return
+ }
+
+ disposed = true
+ cancelFrame()
+ pauseController.dispose()
+ },
+ isDormant: () => dormant,
+ wake
+ }
+}