The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(desktop): exercise the spinner CSS and the invalidation scope for real
Royalaid026950425034
diff --git a/apps/desktop/e2e/glyph-spinner.spec.ts b/apps/desktop/e2e/glyph-spinner.spec.tsnew file mode 100644index 00000000000..e920daa143b--- /dev/null+++ b/apps/desktop/e2e/glyph-spinner.spec.ts@@ -0,0 +1,191 @@+/**+ * E2E contract for the compositor-only GlyphSpinner.+ *+ * The spinner's whole reason for existing in this shape is a CSS animation:+ * every frame is in the DOM from mount and a `transform` keyframes animation+ * scrolls between them, so there is no JS timer and no per-tick DOM mutation+ * scheduling document-scale style recalculation.+ *+ * None of that is observable in jsdom — it has no animation engine, no+ * cascade resolution for `steps()`, and no `Element.getAnimations()`. The+ * jsdom suite (src/components/ui/glyph-spinner.test.tsx) therefore pins the+ * DATA and WIRING, and this spec pins the RENDERED BEHAVIOUR in a real+ * browser, which is the only place the stylesheet actually runs.+ *+ * This replaces three tests that asserted on the TEXT of the stylesheet.+ * Reading source in a test is banned outright (AGENTS.md) and those tests+ * proved the point: a var()-fallback edit that changed no rendered pixel+ * broke one of them, while none of them had ever executed the CSS.+ *+ * Prerequisite: `npm run build` must have been run so dist/ exists.+ */++import { expect, test, type Page } from '@playwright/test'++import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures'++const STRIP = '.glyph-spinner__strip'++/**+ * Send a message so a turn is in flight — the composer status stack mounts a+ * GlyphSpinner while the agent is working. Resolves once a frame strip is in+ * the DOM.+ */+async function mountSpinner(page: Page): Promise<void> {+ const composer = page.locator('[contenteditable="true"]').first()+ await composer.waitFor({ state: 'visible', timeout: 10_000 })+ await composer.click()+ await composer.type('hello from the glyph spinner spec', { delay: 10 })+ await page.keyboard.press('Enter')++ await page.waitForSelector(STRIP, { state: 'attached', timeout: 20_000 })+}++test.describe('GlyphSpinner (compositor animation)', () => {+ let fixture: MockBackendFixture++ test.beforeAll(async () => {+ fixture = await setupMockBackend()+ await waitForAppReady(fixture)+ })++ test.afterAll(async () => {+ await fixture?.cleanup()+ })++ test('animates with a steps() transform keyframes animation, one step per frame', async () => {+ const { page } = fixture+ await mountSpinner(page)++ const observed = await page.evaluate(strip => {+ const el = document.querySelector<HTMLElement>(strip)++ if (!el) {+ throw new Error('no frame strip in the DOM')+ }++ const style = getComputedStyle(el)+ const animations = el.getAnimations()++ return {+ frameCount: el.querySelectorAll('.glyph-spinner__frame').length,+ timingFunction: style.animationTimingFunction,+ iterationCount: style.animationIterationCount,+ durationMs: animations[0]?.effect?.getTiming().duration ?? null,+ names: animations.map(a => (a as CSSAnimation).animationName),+ // A percentage translate makes the animation layout-dependent, which+ // Chromium refuses to composite. The travel must resolve to a length.+ transform: style.transform+ }+ }, STRIP)++ // The strip carries every frame; `steps(N)` parks on each one in turn.+ expect(observed.frameCount).toBeGreaterThan(1)+ // Chromium has serialized jump-end as both `steps(N)` and `steps(N, end)`.+ expect(observed.timingFunction).toMatch(new RegExp(`^steps\\(${observed.frameCount}\\b`))+ expect(observed.iterationCount).toBe('infinite')+ expect(observed.names).toContain('glyph-spinner-advance')+ // One full cycle is frames x interval, so the duration must be a positive+ // multiple of the frame count — not the single-frame interval.+ expect(observed.durationMs).toBeGreaterThan(0)+ // A resolved matrix, never a percentage: `translateY(-100%)` would keep+ // the animation off the compositor.+ expect(observed.transform).not.toContain('%')+ })++ test('is promoted to a layer while running, and neither animates nor holds a layer when parked', async () => {+ const { page } = fixture+ await mountSpinner(page)++ const running = await page.evaluate(strip => {+ const el = document.querySelector<HTMLElement>(strip)!++ return {+ playState: getComputedStyle(el).animationPlayState,+ willChange: getComputedStyle(el).willChange+ }+ }, STRIP)++ expect(running.playState).toBe('running')+ // Scoped to active spinners — a permanently promoted layer per parked+ // spinner is pure memory at fan-out breadth.+ expect(running.willChange).toBe('transform')++ // 1. The per-spinner gate: a kept-alive but inactive pane, or an explicit+ // `paused` prop (ChatSwapOverlay's fade-out).+ const parked = await page.evaluate(strip => {+ const el = document.querySelector<HTMLElement>(strip)!+ const viewport = el.closest<HTMLElement>('.glyph-spinner')!+ const previous = viewport.getAttribute('data-paused')++ viewport.setAttribute('data-paused', 'true')+ const state = {+ playState: getComputedStyle(el).animationPlayState,+ willChange: getComputedStyle(el).willChange+ }++ if (previous === null) {+ viewport.removeAttribute('data-paused')+ } else {+ viewport.setAttribute('data-paused', previous)+ }++ return state+ }, STRIP)++ expect(parked.playState).toBe('paused')+ expect(parked.willChange).toBe('auto')++ // 2. The global gate: window blur / minimize / document-hidden, which+ // main.tsx drives by arming this attribute on the root. The strip must+ // be named in that rule, or every spinner keeps animating behind an+ // inactive window — the CPU burn the original ticker's pause+ // controller existed to avoid.+ const globallyPaused = await page.evaluate(strip => {+ const root = document.documentElement+ const had = root.hasAttribute('data-renderer-animations-paused')++ root.setAttribute('data-renderer-animations-paused', '')+ const playState = getComputedStyle(document.querySelector<HTMLElement>(strip)!).animationPlayState++ if (!had) {+ root.removeAttribute('data-renderer-animations-paused')+ }++ return playState+ }, STRIP)++ expect(globallyPaused).toBe('paused')+ })++ test('advances in discrete frames and creates no timer-driven DOM churn', async () => {+ const { page } = fixture+ await mountSpinner(page)++ // Sample the resolved transform across one full cycle. A steps() animation+ // holds each value for a whole interval and jumps between them, so the+ // distinct values it visits must be bounded by the frame count — a linear+ // animation would produce a new value on every sample.+ const sampled = await page.evaluate(async strip => {+ const el = document.querySelector<HTMLElement>(strip)!+ const frames = el.querySelectorAll('.glyph-spinner__frame').length+ const duration = Number(el.getAnimations()[0]?.effect?.getTiming().duration ?? 0)+ const seen = new Set<string>()+ const textAtStart = el.textContent++ const deadline = performance.now() + duration+ while (performance.now() < deadline) {+ seen.add(getComputedStyle(el).transform)+ await new Promise(resolve => requestAnimationFrame(() => resolve(null)))+ }++ return { distinct: seen.size, frames, textUnchanged: el.textContent === textAtStart }+ }, STRIP)++ expect(sampled.distinct).toBeGreaterThan(1)+ expect(sampled.distinct).toBeLessThanOrEqual(sampled.frames + 1)+ // The old implementation rewrote textContent ~12x/second. Nothing may+ // mutate the DOM as this animates — that mutation is the whole incident.+ expect(sampled.textUnchanged).toBe(true)+ })+})diff --git a/apps/desktop/src/components/assistant-ui/thread/status-invalidation-scope.test.tsx b/apps/desktop/src/components/assistant-ui/thread/status-invalidation-scope.test.tsxnew file mode 100644index 00000000000..435fe9dee47--- /dev/null+++ b/apps/desktop/src/components/assistant-ui/thread/status-invalidation-scope.test.tsx@@ -0,0 +1,164 @@+// The invalidation-scoping property, as a render-count contract.+//+// A streaming turn flips its message status many times a second, and at+// stream breadth N that is N status flips per flush. The whole point of this+// work is that a flip re-renders only the small leaves that actually display+// status — never the message ROOT, whose subtree is the entire rendered+// message and whose re-render is what widened style recalculation to document+// scope.+//+// That property is invisible to a DOM assertion: the transcript looks+// identical either way. So this counts renders instead. AssistantMessageBody+// is the root component, and `useTapbackDoubleClick` is called by it and by+// nothing else in the tree, which makes it an exact render counter for the+// root without needing to export or wrap an internal component.+import { AssistantRuntimeProvider, type ThreadMessage, useExternalStoreRuntime } from '@assistant-ui/react'+import { cleanup, render, waitFor } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { Thread } from '.'++let rootRenders = 0++vi.mock('@/components/assistant-ui/thread/use-message-reactions', async importActual => {+ const actual = await importActual<typeof import('@/components/assistant-ui/thread/use-message-reactions')>()++ return {+ ...actual,+ useTapbackDoubleClick: (messageId: string, role: 'assistant' | 'user') => {+ if (role === 'assistant') {+ rootRenders += 1+ }++ return actual.useTapbackDoubleClick(messageId, role)+ }+ }+})++const createdAt = new Date('2026-05-01T00:00:00.000Z')++class TestResizeObserver {+ observe() {}+ unobserve() {}+ disconnect() {}+}+vi.stubGlobal('ResizeObserver', TestResizeObserver)+vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>+ window.setTimeout(() => callback(performance.now()), 0)+)+vi.stubGlobal('cancelAnimationFrame', (id: number) => window.clearTimeout(id))+vi.stubGlobal('CSS', { escape: (str: string) => str })++Element.prototype.scrollTo = function scrollTo() {}++Element.prototype.animate = function animate() {+ return { cancel() {}, finished: Promise.resolve() } as unknown as Animation+}++beforeEach(() => {+ rootRenders = 0+})++afterEach(() => {+ cleanup()+})++const assistantMetadata = { unstable_state: null, unstable_annotations: [], unstable_data: [], steps: [], custom: {} }++function user(id: string, text: string): ThreadMessage {+ return {+ id,+ role: 'user',+ content: [{ type: 'text', text }],+ attachments: [],+ createdAt,+ metadata: { custom: {} }+ } as ThreadMessage+}++function assistant(id: string, text: string, running: boolean): ThreadMessage {+ return {+ id,+ role: 'assistant',+ content: text ? [{ type: 'text', text }] : [],+ status: running ? { type: 'running' } : { type: 'complete', reason: 'stop' },+ createdAt,+ metadata: assistantMetadata+ } as ThreadMessage+}++function Harness({ messages }: { messages: ThreadMessage[] }) {+ const runtime = useExternalStoreRuntime<ThreadMessage>({+ messages,+ isRunning: messages.at(-1)?.status?.type === 'running',+ onNew: async () => {}+ })++ return (+ <AssistantRuntimeProvider runtime={runtime}>+ <Thread />+ </AssistantRuntimeProvider>+ )+}++describe('streaming-status invalidation scope', () => {+ it('does not re-render the message root when the turn settles', async () => {+ const messages = [user('u1', 'question'), assistant('a1', 'partial answer', true)]+ const { container, findByText, rerender } = render(<Harness messages={messages} />)++ await findByText('partial answer')+ // The leaf carries the streaming flag while the turn is in flight.+ expect(container.querySelector('[data-message-streaming="true"]')).toBeTruthy()++ const rendersWhileStreaming = rootRenders++ rerender(<Harness messages={[messages[0], assistant('a1', 'partial answer', false)]} />)++ // The leaf saw the flip...+ await waitFor(() => {+ expect(container.querySelector('[data-message-streaming="true"]')).toBeNull()+ })+ // ...on the same permanently-mounted node (attribute toggle, no remount)...+ expect(container.querySelector('[data-slot="aui_message-streaming-marker"]')).toBeTruthy()+ // ...and the root did not re-render for it.+ expect(rootRenders).toBe(rendersWhileStreaming)+ })++ it('does not re-render the message root when streaming text arrives', async () => {+ const messages = [user('u1', 'question'), assistant('a1', 'one', true)]+ const { findByText, rerender } = render(<Harness messages={messages} />)++ await findByText('one')+ const rendersAfterFirstToken = rootRenders++ // A delta flush: same status, more text. The root must not subscribe to+ // the streaming text either — only the markdown part re-renders.+ rerender(<Harness messages={[messages[0], assistant('a1', 'one two', true)]} />)+ await findByText('one two')++ expect(rootRenders).toBe(rendersAfterFirstToken)+ })++ it('keeps the same root DOM node across the settle transition', async () => {+ // The inter-agent reply collapses once it settles. Rendering that as a+ // competing root swapped the element type at this position, so React+ // unmounted the row and mounted a fresh one — discarding the DOM the+ // scroll anchor was holding.+ const delivery = 'Message from 🤖 Hermes (@hermes): please check the build'+ const messages = [user('u1', delivery), assistant('a1', 'working on it', true)]+ const { container, findByText, rerender } = render(<Harness messages={messages} />)++ await findByText('working on it')+ const before = container.querySelector('[data-slot="aui_assistant-message-root"]')++ expect(before).toBeTruthy()++ rerender(<Harness messages={[messages[0], assistant('a1', 'working on it', false)]} />)+ await findByText(/Replied to/)++ const after = container.querySelector('[data-slot="aui_assistant-message-root"]')++ // Same element, updated in place — not a remount.+ expect(after).toBe(before)+ })+})diff --git a/apps/desktop/src/components/ui/glyph-spinner.test.tsx b/apps/desktop/src/components/ui/glyph-spinner.test.tsxindex 2ae3260cff2..99f21983e77 100644--- a/apps/desktop/src/components/ui/glyph-spinner.test.tsx+++ b/apps/desktop/src/components/ui/glyph-spinner.test.tsx@@ -2,8 +2,7 @@// 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).+// style recalculation on every tick.//// 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@@ -153,5 +152,4 @@ describe('GlyphSpinner', () => {expect(viewport()?.hasAttribute('data-paused')).toBe(false)})-})