The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(desktop): stop scroll and status loops in busy sessions
Mykola Bashmakov7700597a1707
diff --git a/apps/desktop/src/app/chat/session-status-dot.tsx b/apps/desktop/src/app/chat/session-status-dot.tsxindex 09fb7773a87..c84a1cae0dd 100644--- a/apps/desktop/src/app/chat/session-status-dot.tsx+++ b/apps/desktop/src/app/chat/session-status-dot.tsx@@ -1,5 +1,6 @@import { useStore } from '@nanostores/react'+import { StatusPulse } from '@/components/ui/status-pulse'import { type Translations, useI18n } from '@/i18n'import { useStoreSelector } from '@/lib/use-session-slice'import { cn } from '@/lib/utils'@@ -17,6 +18,10 @@ import { type SessionDotState, sessionDotState } from './sidebar/session-row-statype DotVariant = {ariaLabel?: (r: Translations['sidebar']['row']) => stringclassName: string+ pulse?: {+ className: string+ opacity: number+ }role?: 'status'title?: (r: Translations['sidebar']['row']) => string}@@ -24,12 +29,6 @@ type DotVariant = {// Shared base for every active dot; idle is smaller and uses its own class.const DOT_BASE = 'relative size-1.5 rounded-full'-// Pseudo-element ping ring that scales outward and fades — shared scaffold for-// the two pulsing dots. The `before:bg-*` color is written inline per variant-// (NOT interpolated here): Tailwind only generates utilities it can see as-// complete static strings, so a `before:bg-${color}` template never emits.-const PING = "before:absolute before:inset-0 before:animate-ping before:rounded-full before:content-['']"-const DOT_VARIANTS: Record<SessionDotState, DotVariant> = {// Amber steady — a clarify/approval is blocking the turn. Steady (not// pulsing) reads as "your turn", distinct from the accent pulse of a turn.@@ -42,14 +41,22 @@ const DOT_VARIANTS: Record<SessionDotState, DotVariant> = {// Accent pulse — the LLM turn is actively running.working: {ariaLabel: r => r.sessionRunning,- className: `${DOT_BASE} bg-(--ui-accent) shadow-[0_0_0.625rem_color-mix(in_srgb,var(--ui-accent)_55%,transparent)] ${PING} before:bg-(--ui-accent) before:opacity-70`,+ className: `${DOT_BASE} bg-(--ui-accent) shadow-[0_0_0.625rem_color-mix(in_srgb,var(--ui-accent)_55%,transparent)]`,+ pulse: {+ className: 'absolute inset-0 rounded-full bg-(--ui-accent) opacity-0',+ opacity: 0.7+ },role: 'status'},// Quiet accent pulse — the turn is still authoritative-running, but no// stream activity has arrived for the watchdog window.stalled: {ariaLabel: r => r.sessionRunning,- className: `${DOT_BASE} bg-(--ui-accent) opacity-70 ${PING} before:bg-(--ui-accent) before:opacity-40`,+ className: `${DOT_BASE} bg-(--ui-accent) opacity-70`,+ pulse: {+ className: 'absolute inset-0 rounded-full bg-(--ui-accent) opacity-0',+ opacity: 0.4+ },role: 'status',title: r => r.sessionRunning},@@ -58,7 +65,11 @@ const DOT_VARIANTS: Record<SessionDotState, DotVariant> = {// than muted-foreground so it's visible against the surface.background: {ariaLabel: r => r.backgroundRunning,- className: `${DOT_BASE} bg-muted-foreground/80 ${PING} before:bg-muted-foreground/80 before:opacity-60`,+ className: `${DOT_BASE} bg-muted-foreground/80`,+ pulse: {+ className: 'absolute inset-0 rounded-full bg-muted-foreground/80 opacity-0',+ opacity: 0.6+ },role: 'status',title: r => r.backgroundRunning},@@ -123,6 +134,7 @@ export function SessionStatusDot({ storedSessionId, session, branchStem, classNaconst hasBackground = useStoreSelector($backgroundRunningSessionIds, ids => ids.includes(storedSessionId))const dotState = sessionDotState({ hasBackground, isStalled, isUnread, isWorking, needsInput })+ const variant = DOT_VARIANTS[dotState]return (<span className={cn('flex items-center gap-0.5', className)}>@@ -135,11 +147,20 @@ export function SessionStatusDot({ storedSessionId, session, branchStem, classNa<span aria-hidden="true" className="size-1 rounded-full" style={{ backgroundColor: color }} />) : (<span- aria-label={DOT_VARIANTS[dotState].ariaLabel?.(r)}- className={DOT_VARIANTS[dotState].className}- role={DOT_VARIANTS[dotState].role}- title={DOT_VARIANTS[dotState].title?.(r)}- />+ aria-label={variant.ariaLabel?.(r)}+ className={variant.className}+ role={variant.role}+ title={variant.title?.(r)}+ >+ {variant.pulse ? (+ <StatusPulse+ aria-hidden="true"+ className={variant.pulse.className}+ kind="ping"+ opacity={variant.pulse.opacity}+ />+ ) : null}+ </span>)}</span>)diff --git a/apps/desktop/src/components/assistant-ui/thread/list.test.ts b/apps/desktop/src/components/assistant-ui/thread/list.test.tsindex 413aab88650..c0cd1da5588 100644--- a/apps/desktop/src/components/assistant-ui/thread/list.test.ts+++ b/apps/desktop/src/components/assistant-ui/thread/list.test.ts@@ -8,7 +8,8 @@ import {liveTailStart,type MessageGroup,messageRenderWeight,- RENDER_WEIGHT_CHARS+ RENDER_WEIGHT_CHARS,+ resolveThreadScrollTarget} from './list'// Signature rows are `${index}:${id}:${role}:${weight}` (see the useAuiState@@ -62,6 +63,53 @@ describe('buildGroups', () => {})})+describe('resolveThreadScrollTarget', () => {+ const context = (scrollElement: Pick<HTMLElement, 'scrollTop'>) => ({+ contentElement: document.createElement('div'),+ scrollElement: scrollElement as HTMLElement+ })++ it('settles when the browser clamps the requested bottom within half a CSS pixel', () => {+ let actualScrollTop = 0+ let writes = 0++ const scrollElement = {+ get scrollTop() {+ return actualScrollTop+ },+ set scrollTop(value: number) {+ writes += 1+ actualScrollTop = value - 0.125+ }+ }++ const target = 899++ const requested = resolveThreadScrollTarget(target, context(scrollElement))+ scrollElement.scrollTop = requested+ const settled = resolveThreadScrollTarget(target, context(scrollElement))++ expect(requested).toBe(target)+ expect(actualScrollTop).toBe(898.875)+ expect(settled).toBe(actualScrollTop)+ expect(actualScrollTop < settled).toBe(false)+ expect(writes).toBe(1)+ })++ it('keeps following while more than half a CSS pixel remains', () => {+ const scrollElement = { scrollTop: 898.25 }++ expect(resolveThreadScrollTarget(899, context(scrollElement))).toBe(899)+ })++ it('re-arms after streaming content increases the target', () => {+ const scrollElement = { scrollTop: 898.875 }++ expect(resolveThreadScrollTarget(899, context(scrollElement))).toBe(898.875)+ expect(resolveThreadScrollTarget(999, context(scrollElement))).toBe(999)+ })+})+describe('firstVisibleGroupIndex', () => {const group = (id: string, weight: number): MessageGroup => ({ id, index: 0, kind: 'standalone', weight })diff --git a/apps/desktop/src/components/assistant-ui/thread/list.tsx b/apps/desktop/src/components/assistant-ui/thread/list.tsxindex faa07248832..d8fd0f0a5c6 100644--- a/apps/desktop/src/components/assistant-ui/thread/list.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/list.tsx@@ -13,7 +13,7 @@ import {useRef,useState} from 'react'-import { useStickToBottom } from 'use-stick-to-bottom'+import { type GetTargetScrollTop, useStickToBottom } from 'use-stick-to-bottom'import { useI18n } from '@/i18n'import { cn } from '@/lib/utils'@@ -62,6 +62,20 @@ const MAX_MEASURED_MESSAGE_CHARS = RENDER_BUDGET * RENDER_WEIGHT_CHARS// blocks the click-to-paint path.const FIRST_PAINT_BUDGET = 20+// Browsers may quantize a requested scrollTop to a nearby device-pixel+// boundary. use-stick-to-bottom otherwise compares the lower actual value to+// the integer target forever, re-requesting the same instant scroll every+// frame. Treat a subpixel remainder as achieved; larger gaps still follow new+// streamed content normally.+const SCROLL_TARGET_EPSILON_PX = 0.5++export const resolveThreadScrollTarget: GetTargetScrollTop = (targetScrollTop, { scrollElement }) => {+ const currentScrollTop = scrollElement.scrollTop+ const remaining = targetScrollTop - currentScrollTop++ return remaining >= 0 && remaining <= SCROLL_TARGET_EPSILON_PX ? currentScrollTop : targetScrollTop+}+const contentWeightCache = new WeakMap<object, number>()const NON_RENDERED_CONTENT_FIELDS = new Set(['id', 'role', 'toolCallId', 'toolName', 'type'])@@ -297,7 +311,8 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({// settling. Its refs hang off our own DOM so the sticky human bubbles survive.const { scrollRef, contentRef, isAtBottom, scrollToBottom, stopScroll } = useStickToBottom({initial: 'instant',- resize: 'instant'+ resize: 'instant',+ targetScrollTop: resolveThreadScrollTarget})const [renderBudget, setRenderBudget] = useState(FIRST_PAINT_BUDGET)diff --git a/apps/desktop/src/components/assistant-ui/thread/status.tsx b/apps/desktop/src/components/assistant-ui/thread/status.tsxindex 83cd107a292..492a73b1f1d 100644--- a/apps/desktop/src/components/assistant-ui/thread/status.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/status.tsx@@ -9,6 +9,7 @@ import { ActivityTimerText } from '@/components/chat/activity-timer-text'import { SCAFFOLD_LABEL_CLASS } from '@/components/chat/scaffold-row'import { Codicon } from '@/components/ui/codicon'import { Loader } from '@/components/ui/loader'+import { StatusPulse } from '@/components/ui/status-pulse'import { useI18n } from '@/i18n'import { cn } from '@/lib/utils'import { $backgroundResume } from '@/store/background-delegation'@@ -130,7 +131,11 @@ export const ResponseLoadingIndicator: FC = () => {return (<StatusRow data-slot="aui_response-loading" label={hint || t.assistant.thread.loadingResponse}>- <span aria-hidden="true" className="dither inline-block size-3 rounded-[2px] text-midground/80 animate-pulse" />+ <StatusPulse+ aria-hidden="true"+ className="dither inline-block size-3 rounded-[2px] text-midground/80"+ kind="opacity"+ />{hint && <HintText>{hint}</HintText>}<ActivityTimerText seconds={elapsed} /></StatusRow>@@ -236,7 +241,11 @@ export const StreamStallIndicator: FC = () => {return (<StatusRow data-slot="aui_stream-stall" label={hint || 'Hermes is thinking'}>- <span aria-hidden="true" className="dither inline-block size-3 rounded-[2px] text-midground/80 animate-pulse" />+ <StatusPulse+ aria-hidden="true"+ className="dither inline-block size-3 rounded-[2px] text-midground/80"+ kind="opacity"+ />{hint && <HintText>{hint}</HintText>}<ActivityTimerText seconds={elapsed} /></StatusRow>diff --git a/apps/desktop/src/components/ui/status-pulse.test.tsx b/apps/desktop/src/components/ui/status-pulse.test.tsxnew file mode 100644index 00000000000..8f496229289--- /dev/null+++ b/apps/desktop/src/components/ui/status-pulse.test.tsx@@ -0,0 +1,131 @@+import { act, cleanup, render } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { StatusPulse } from './status-pulse'++interface PlayedAnimation {+ cancel: ReturnType<typeof vi.fn>+ keyframes: Keyframe[]+ options: KeyframeAnimationOptions+}++interface WindowStatePayload {+ isMinimized?: boolean+ isVisible?: boolean+}++let windowStateCallback: ((payload: WindowStatePayload) => void) | undefined++function installMatchMedia(matches: boolean) {+ vi.stubGlobal(+ 'matchMedia',+ vi.fn(() => ({+ addEventListener: vi.fn(),+ matches,+ media: '(prefers-reduced-motion: reduce)',+ onchange: null,+ removeEventListener: vi.fn()+ }))+ )+}++function installWindowStateBridge() {+ const off = vi.fn()++ window.hermesDesktop = {+ onWindowStateChanged: vi.fn(callback => {+ windowStateCallback = callback++ return off+ })+ } as unknown as typeof window.hermesDesktop++ return off+}++describe('StatusPulse', () => {+ const played: PlayedAnimation[] = []++ beforeEach(() => {+ vi.useFakeTimers()+ vi.spyOn(window.document, 'hasFocus').mockReturnValue(true)+ installMatchMedia(false)+ installWindowStateBridge()+ Object.defineProperty(HTMLElement.prototype, 'animate', {+ configurable: true,+ value: (keyframes: Keyframe[], options: KeyframeAnimationOptions) => {+ const animation = {+ cancel: vi.fn(),+ keyframes,+ options+ }++ played.push(animation)++ return animation as unknown as Animation+ },+ writable: true+ })+ })++ afterEach(() => {+ cleanup()+ played.length = 0+ windowStateCallback = undefined+ Reflect.deleteProperty(HTMLElement.prototype, 'animate')+ delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop+ vi.useRealTimers()+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+ })++ it('plays a finite ping and sleeps between pulses', () => {+ render(<StatusPulse kind="ping" opacity={0.7} />)++ expect(played).toHaveLength(1)+ expect(played[0]?.keyframes).toEqual([+ { opacity: 0.7, transform: 'scale(1)' },+ { opacity: 0, transform: 'scale(2)' }+ ])+ expect(played[0]?.options).toMatchObject({ duration: 400, iterations: 1 })+ expect(vi.getTimerCount()).toBe(1)++ act(() => vi.advanceTimersByTime(4_999))+ expect(played).toHaveLength(1)++ act(() => vi.advanceTimersByTime(1))+ expect(played).toHaveLength(2)+ })++ it('cancels scheduled work while minimized and restarts once visible', () => {+ const offWindowState = installWindowStateBridge()+ const mounted = render(<StatusPulse kind="opacity" />)++ expect(played).toHaveLength(1)++ act(() => windowStateCallback?.({ isMinimized: true, isVisible: false }))++ expect(played[0]?.cancel).toHaveBeenCalledTimes(1)+ expect(vi.getTimerCount()).toBe(0)++ act(() => vi.advanceTimersByTime(5_000))+ expect(played).toHaveLength(1)++ act(() => windowStateCallback?.({ isMinimized: false, isVisible: true }))+ expect(played).toHaveLength(2)++ mounted.unmount()+ expect(played[1]?.cancel).toHaveBeenCalledTimes(1)+ expect(offWindowState).toHaveBeenCalledTimes(1)+ expect(vi.getTimerCount()).toBe(0)+ })++ it('stays static when reduced motion is requested', () => {+ installMatchMedia(true)++ render(<StatusPulse kind="opacity" />)++ expect(played).toHaveLength(0)+ expect(vi.getTimerCount()).toBe(0)+ })+})diff --git a/apps/desktop/src/components/ui/status-pulse.tsx b/apps/desktop/src/components/ui/status-pulse.tsxnew file mode 100644index 00000000000..570d084cdc9--- /dev/null+++ b/apps/desktop/src/components/ui/status-pulse.tsx@@ -0,0 +1,93 @@+import { type ComponentProps, useEffect, useRef } from 'react'++import { createRendererLoopPauseController } from '@/lib/renderer-loop-pause'++const PULSE_DURATION_MS = 400+const PULSE_PERIOD_MS = 5_000++export interface StatusPulseProps extends Omit<ComponentProps<'span'>, 'children' | 'ref'> {+ kind: 'opacity' | 'ping'+ opacity?: number+}++/**+ * A finite status pulse with a real sleep between plays.+ *+ * Continuous CSS animations keep Chromium producing frames and recalculating+ * styles for an otherwise motionless Desktop window. Drive the same visual+ * cue directly so React stays out of the loop and the renderer/compositor can+ * sleep between pulses.+ */+export function StatusPulse({ kind, opacity = 1, ...props }: StatusPulseProps) {+ const ref = useRef<HTMLSpanElement>(null)++ useEffect(() => {+ const element = ref.current++ if (+ !element ||+ typeof element.animate !== 'function' ||+ window.matchMedia?.('(prefers-reduced-motion: reduce)').matches+ ) {+ return+ }++ let animation: Animation | null = null+ let timer = 0+ let stopped = false+ let pauseController: ReturnType<typeof createRendererLoopPauseController> | null = null++ const clearScheduled = () => {+ if (timer !== 0) {+ window.clearTimeout(timer)+ timer = 0+ }++ animation?.cancel()+ animation = null+ }++ const play = () => {+ timer = 0++ if (stopped || pauseController?.isPaused()) {+ return+ }++ animation?.cancel()+ animation = element.animate(+ kind === 'ping'+ ? [+ { opacity, transform: 'scale(1)' },+ { opacity: 0, transform: 'scale(2)' }+ ]+ : [{ opacity: 1 }, { opacity: 0.5 }, { opacity: 1 }],+ {+ duration: PULSE_DURATION_MS,+ easing: kind === 'ping' ? 'cubic-bezier(0, 0, 0.2, 1)' : 'ease-in-out',+ iterations: 1+ }+ )+ timer = window.setTimeout(play, PULSE_PERIOD_MS)+ }++ const handlePauseChange = () => {+ clearScheduled()++ if (!pauseController?.isPaused()) {+ play()+ }+ }++ pauseController = createRendererLoopPauseController(handlePauseChange)+ play()++ return () => {+ stopped = true+ clearScheduled()+ pauseController?.dispose()+ }+ }, [kind, opacity])++ return <span {...props} ref={ref} />+}