graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Improve desktop motion and release inactive animations
Rach Pradhan9fc3dc30a160
diff --git a/apps/native/README.md b/apps/native/README.mdindex f0675d2f..d9b71e5b 100644--- a/apps/native/README.md+++ b/apps/native/README.md@@ -29,8 +29,9 @@ Dropped:here, so SidebarNav uses the free stroke set in `lib/icons.tsx`- Ice-cream `SCENARIOS` / `matchScenario` demo data-Kept (free): `tailwindcss` v4, `shadow-plugin`, `glimm` (prompt-bar sweep),-`iconoir-react`, `liveline`.+Kept (free): `tailwindcss` v4, `shadow-plugin`, `iconoir-react`, `liveline`.+The prompt-bar feedback uses a short native browser animation; it does not+allocate a shader canvas.## How the harness talks to graffdiff --git a/apps/native/app/globals.css b/apps/native/app/globals.cssindex 8d5db831..2a481378 100644--- a/apps/native/app/globals.css+++ b/apps/native/app/globals.css@@ -397,32 +397,6 @@ a:focus-visible .animated-underline::after {border-radius: var(--radius-control);}-/* ── shared keyframes ─────────────────────────────────── */--@keyframes shimmer-text {- from {- background-position: 150% center;- }- to {- background-position: -50% center;- }-}--@keyframes fade-up {- from {- opacity: 0;- transform: translateY(8px);- }- to {- opacity: 1;- transform: translateY(0);- }-}--.home-reveal {- will-change: opacity, transform, filter;-}-/* The sidebar is one persistent 224px tree clipped by a 52px shell.* Every rail glyph remains centered at x=26 in both states. */.sidebar-row {@@ -486,14 +460,6 @@ a:focus-visible .animated-underline::after {width: 36px;}-@media (prefers-reduced-motion: reduce) {- .home-reveal {- opacity: 1 !important;- transform: none !important;- filter: none !important;- }-}-/* ── records table ────────────────────────────────────────* The grid is deliberately more architectural than card-like:* one quiet surface, precise rules, and color reserved for@@ -1409,110 +1375,3 @@ th.is-colsel .records-header-icon {background: color-mix(in srgb, var(--tag-base) 34%, var(--surface));border-color: color-mix(in srgb, var(--tag-base) 34%, var(--surface));}--@keyframes fade-in {- from {- opacity: 0;- }- to {- opacity: 1;- }-}--@keyframes eq-bounce {- 0%,- 100% {- transform: scaleY(0.35);- }- 50% {- transform: scaleY(1);- }-}--/* ── StreamText primitive ─────────────────────────────────- * Fast character reveal: the newest few characters carry a- * soft, masked blur so the leading edge resolves smoothly as- * text flows in. The caret holds solid while streaming, then- * blinks once the string settles. */-.stream-tail {- filter: blur(1.6px);- -webkit-mask-image: linear-gradient(to right, oklch(0 0 0) 20%, oklch(0 0 0 / 0.2));- mask-image: linear-gradient(to right, oklch(0 0 0) 20%, oklch(0 0 0 / 0.2));-}--.stream-caret {- display: inline-block;- width: 2px;- height: 1.05em;- margin-left: 1.5px;- translate: 0 -0.5px;- border-radius: 1px;- background: var(--ink);- vertical-align: text-bottom;- animation: caret-blink 1s step-end infinite;-}--.stream-caret.is-streaming {- animation: none;-}--@keyframes caret-blink {- 0%,- 100% {- opacity: 1;- }- 50% {- opacity: 0;- }-}--@media (prefers-reduced-motion: reduce) {- .stream-caret {- animation: none;- }- .stream-tail {- filter: none;- -webkit-mask-image: none;- mask-image: none;- }-}--@keyframes pop-in {- from {- opacity: 0;- transform: scale(0.95);- }- to {- opacity: 1;- transform: scale(1);- }-}--@keyframes spin {- to {- transform: rotate(360deg);- }-}--/* pixel-grid loader — brighten plateau, staggered per cell */-@keyframes pixel-on {- 0%, 100% {- opacity: 0.15;- }- 18%, 42% {- opacity: 1;- }- 62% {- opacity: 0.15;- }-}--@media (prefers-reduced-motion: reduce) {- *,- *::before,- *::after {- animation-duration: 0.01ms !important;- animation-iteration-count: 1 !important;- transition-duration: 0.01ms !important;- }-}diff --git a/apps/native/app/layout.tsx b/apps/native/app/layout.tsxindex 73f39d26..10d1ae0d 100644--- a/apps/native/app/layout.tsx+++ b/apps/native/app/layout.tsx@@ -2,6 +2,8 @@ import type { Metadata } from "next";import { Geist, Geist_Mono } from "next/font/google";import "./globals.css";import "./appearance.css";+import "./motion.css";+import { MotionLifecycle } from "@/components/site/MotionLifecycle";import { appearanceScript } from "@/lib/appearance";import { ThemeSync } from "@/components/site/ThemeSync";import DesktopTitlebar from "@/components/site/DesktopTitlebar";@@ -34,6 +36,7 @@ export default function RootLayout({</head><body className={`${inter.variable} ${mono.variable} font-sans`}><ThemeSync />+ <MotionLifecycle /><BrowserWarm /><DesktopTitlebar /><DesktopUpdates />diff --git a/apps/native/app/motion.css b/apps/native/app/motion.cssnew file mode 100644index 00000000..a3fa07c1--- /dev/null+++ b/apps/native/app/motion.css@@ -0,0 +1,176 @@+/* Short, event-driven motion. Finished entrances release their transform layer. */+:root {+ --motion-fast: 120ms;+ --motion-enter: 180ms;+ --motion-settle: 240ms;+ --motion-ease: cubic-bezier(0.2, 0.8, 0.2, 1);+}++/* Existing activity labels use a static gradient; only opacity changes. */+@keyframes shimmer-text {+ 0%, 100% { opacity: 1; }+ 50% { opacity: 0.6; }+}++@keyframes fade-up {+ from { opacity: 0; transform: translateY(6px); }+ to { opacity: 1; transform: none; }+}++.home-reveal {+ animation: fade-up 320ms var(--motion-ease) backwards;+}+.home-reveal-title { animation-delay: 35ms; }+.home-reveal-composer { animation-delay: 65ms; }+.home-reveal-suggestions { animation-delay: 95ms; }++.motion-surface {+ /* Placement and visibility are immediate, including under reduced motion. */+ transition-property: none;+ animation: surface-in var(--motion-enter) var(--motion-ease) backwards;+}+@keyframes surface-in {+ from { opacity: 0; transform: translateY(4px) scale(0.99); }+ to { opacity: 1; transform: none; }+}++/* One small hover layer, no animated layout geometry or persistent promotion. */+.motion-glide {+ transition: transform var(--motion-settle) var(--motion-ease), opacity var(--motion-fast) ease-out;+}++[data-workspace-toolbar] button {+ transition: background-color var(--motion-fast) ease-out, color var(--motion-fast) ease-out,+ scale var(--motion-fast) var(--motion-ease);+}+[data-workspace-toolbar] button:enabled:active { scale: 0.96; }+[data-tab-id] > span.bg-accent {+ animation: tab-marker-in var(--motion-enter) var(--motion-ease) backwards;+}+@keyframes tab-marker-in {+ from { opacity: 0; transform: scaleX(0.7); }+ to { opacity: 1; transform: none; }+}++/* Visibility changes are event-driven: no poller or animation-frame loop. */+html[data-motion-hidden="true"] *,+html[data-motion-hidden="true"] *::before,+html[data-motion-hidden="true"] *::after {+ animation-play-state: paused !important;+}++@keyframes fade-in {+ from {+ opacity: 0;+ }+ to {+ opacity: 1;+ }+}++@keyframes eq-bounce {+ 0%,+ 100% {+ transform: scaleY(0.35);+ }+ 50% {+ transform: scaleY(1);+ }+}++/* ── StreamText primitive ─────────────────────────────────+ * Fast character reveal: the newest few characters carry a+ * soft, masked blur so the leading edge resolves smoothly as+ * text flows in. The caret holds solid while streaming, then+ * blinks once the string settles. */+.stream-tail {+ filter: blur(1.6px);+ -webkit-mask-image: linear-gradient(to right, oklch(0 0 0) 20%, oklch(0 0 0 / 0.2));+ mask-image: linear-gradient(to right, oklch(0 0 0) 20%, oklch(0 0 0 / 0.2));+}++.stream-caret {+ display: inline-block;+ width: 2px;+ height: 1.05em;+ margin-left: 1.5px;+ translate: 0 -0.5px;+ border-radius: 1px;+ background: var(--ink);+ vertical-align: text-bottom;+ animation: caret-blink 1s step-end infinite;+}++.stream-caret.is-streaming {+ animation: none;+}++@keyframes caret-blink {+ 0%,+ 100% {+ opacity: 1;+ }+ 50% {+ opacity: 0;+ }+}++@media (prefers-reduced-motion: reduce) {+ .stream-caret {+ animation: none;+ }+ .stream-tail {+ filter: none;+ -webkit-mask-image: none;+ mask-image: none;+ }+}++@keyframes pop-in {+ from {+ opacity: 0;+ transform: translateY(3px) scale(0.98);+ }+ to {+ opacity: 1;+ transform: none;+ }+}++@keyframes spin {+ to {+ transform: rotate(360deg);+ }+}++/* pixel-grid loader — brighten plateau, staggered per cell */+@keyframes pixel-on {+ 0%, 100% {+ opacity: 0.15;+ }+ 18%, 42% {+ opacity: 1;+ }+ 62% {+ opacity: 0.15;+ }+}++@media (prefers-reduced-motion: reduce) {+ *,+ *::before,+ *::after {+ animation-duration: 0.01ms !important;+ animation-delay: 0ms !important;+ animation-iteration-count: 1 !important;+ /* Zero also prevents transient inherited visibility from rejecting focus. */+ transition-duration: 0s !important;+ transition-delay: 0ms !important;+ scroll-behavior: auto !important;+ }+}++@media (prefers-reduced-motion: reduce) {+ .home-reveal, .motion-surface { animation: none !important; }+ [data-workspace-toolbar] button:enabled:active { scale: none; }+}diff --git a/apps/native/components/primitives/ComposerMenu.tsx b/apps/native/components/primitives/ComposerMenu.tsxindex 76d404cf..b3cd70fb 100644--- a/apps/native/components/primitives/ComposerMenu.tsx+++ b/apps/native/components/primitives/ComposerMenu.tsx@@ -35,7 +35,7 @@ export default function ComposerMenu({ anchor, panel, id, menu, rows, query, actif (row.offsetTop < viewport.scrollTop) viewport.scrollTop = row.offsetTop;else if (row.offsetTop + row.offsetHeight > viewport.scrollTop + viewport.clientHeight) viewport.scrollTop = row.offsetTop + row.offsetHeight - viewport.clientHeight;}, [active, query, position]);- return createPortal(<div ref={panel} data-composer-menu className="fixed z-[200] flex flex-col overflow-hidden rounded-xl border border-line bg-surface p-1 shadow-raised"+ return createPortal(<div ref={panel} data-composer-menu className="motion-surface fixed z-[200] flex flex-col overflow-hidden rounded-xl border border-line bg-surface p-1 shadow-raised"style={{ ...position, visibility: position ? "visible" : "hidden" }} onMouseLeave={() => setEngaged(false)}><div ref={list} id={id} role="listbox" aria-label={menu === "slash" ? "Commands" : menu === "skill" ? "GUI skills" : "Sources and files"} className="relative min-h-0 overflow-y-auto overscroll-contain">{rows.map((row, i) => {@@ -43,7 +43,10 @@ export default function ComposerMenu({ anchor, panel, id, menu, rows, query, actconst mark = source ? source.brand ? BRANDS[source.brand] : <Icon size={15}>{GLYPHS[source.glyph ?? "clip"]}</Icon>: row.key.startsWith("file:") ? <Icon size={15}>{GLYPHS.file}</Icon> : null;return <button key={row.key} id={`${id}-${i}`} type="button" role="option" aria-selected={i === active} title={`${row.name} — ${row.desc}`}- onPointerDown={event => { event.preventDefault(); onPick(row); }} onMouseEnter={() => { setActive(i); setEngaged(true); }}+ onPointerDown={event => { event.preventDefault(); onPick(row); }} onPointerMove={() => {+ if (active !== i) setActive(i);+ if (!engaged) setEngaged(true);+ }}onClick={event => { if (event.detail === 0) onPick(row); }}className={`flex h-9 w-full items-center gap-2.5 rounded-md px-2 text-left ${engaged && i === active ? "bg-hover" : "hover:bg-hover"}`}>{mark && <span className="flex size-5 shrink-0 items-center justify-center text-ink-2">{mark}</span>}diff --git a/apps/native/components/primitives/GlideMenu.tsx b/apps/native/components/primitives/GlideMenu.tsxindex 2487aea9..3527e7af 100644--- a/apps/native/components/primitives/GlideMenu.tsx+++ b/apps/native/components/primitives/GlideMenu.tsx@@ -17,26 +17,35 @@ export default function GlideMenu({rowSelector = "[data-menu-row]",}: GlideMenuProps) {const ref = useRef<HTMLDivElement>(null);+ const highlightedRow = useRef<HTMLElement | null>(null);const [box, setBox] = useState<{ top: number; height: number } | null>(null);const [visible, setVisible] = useState(false);+ const [gliding, setGliding] = useState(false);- const moveTo = (target: EventTarget | null) => {+ const moveTo = (target: EventTarget | null, relatedTarget: EventTarget | null) => {const container = ref.current;if (!(target instanceof Element) || !container) return;const row = target.closest(rowSelector);if (!(row instanceof HTMLElement) || !container.contains(row)) return;+ // Moving across a row's icon and label should not measure or rerender it.+ if (visible && highlightedRow.current === row && relatedTarget instanceof Element+ && relatedTarget.closest(rowSelector) === row) return;+ highlightedRow.current = row;const containerRect = container.getBoundingClientRect();const rowRect = row.getBoundingClientRect();- setBox({ top: rowRect.top - containerRect.top, height: rowRect.height });+ setGliding(visible && box !== null);+ const top = rowRect.top - containerRect.top + container.scrollTop - container.clientTop;+ setBox(previous => previous?.top === top && previous.height === rowRect.height+ ? previous : { top, height: rowRect.height });setVisible(true);};return (<divref={ref}- onMouseOver={(event) => moveTo(event.target)}+ onMouseOver={(event) => moveTo(event.target, event.relatedTarget)}onMouseLeave={() => setVisible(false)}- onFocusCapture={(event) => moveTo(event.target)}+ onFocusCapture={(event) => moveTo(event.target, event.relatedTarget)}onBlurCapture={(event) => {if (!ref.current?.contains(event.relatedTarget as Node | null)) setVisible(false);}}@@ -44,13 +53,14 @@ export default function GlideMenu({><spanaria-hidden- className={`pointer-events-none absolute ${highlightClassName}`}+ className={`motion-glide pointer-events-none absolute ${highlightClassName}`}style={{- top: box?.top ?? 0,+ top: 0,+ transform: `translateY(${box?.top ?? 0}px)`,height: box?.height ?? 0,opacity: box && visible ? 1 : 0,- transition:- "top 220ms cubic-bezier(0.23,1,0.32,1), height 220ms cubic-bezier(0.23,1,0.32,1), opacity 150ms ease",+ // First entry appears at its row; subsequent moves glide between rows.+ transitionProperty: visible && gliding ? undefined : "opacity",}}/>{children}diff --git a/apps/native/components/primitives/ModelEffortButtons.tsx b/apps/native/components/primitives/ModelEffortButtons.tsxindex c2797236..153b5d71 100644--- a/apps/native/components/primitives/ModelEffortButtons.tsx+++ b/apps/native/components/primitives/ModelEffortButtons.tsx@@ -63,7 +63,7 @@ export default function ModelEffortButtons({ model, buttonRef, modelOpen, openMo{levels.length > 0 && <button ref={effortButton} type="button" aria-label="Select effort" aria-expanded={open} onClick={show}className="flex h-7 shrink-0 items-center gap-1.5 rounded-full px-2 text-xs text-ink-3 hover:bg-hover">{labels[model.effort ?? ""] ?? "Effort"}<Chevron /></button>}{open && createPortal(<div ref={panel} role="dialog" aria-label="Reasoning effort" style={position}- className="fixed z-[100] w-80 max-w-[calc(100vw-24px)] rounded-[22px] border border-line bg-page px-4 pb-4 pt-3 text-ink shadow-[0_8px_24px_-8px_rgb(0_0_0/18%)]">+ className="motion-surface fixed z-[100] w-80 max-w-[calc(100vw-24px)] rounded-[22px] border border-line bg-page px-4 pb-4 pt-3 text-ink shadow-[0_8px_24px_-8px_rgb(0_0_0/18%)]"><div className="flex items-center justify-between gap-3"><button type="button" aria-label="Fast mode" aria-pressed={!!model.fast} disabled={blocked || !model.fastSupported}title={model.fastSupported ? "Priority service for lower latency; may use more of your allowance" : "Fast mode is available for Codex models"}diff --git a/apps/native/components/primitives/ModelPicker.tsx b/apps/native/components/primitives/ModelPicker.tsxindex 7f306b9a..4ff52f7c 100644--- a/apps/native/components/primitives/ModelPicker.tsx+++ b/apps/native/components/primitives/ModelPicker.tsx@@ -58,7 +58,7 @@ export default function ModelPicker({ models, selected, anchor, onSelect, onCloselse if (row.offsetTop + row.offsetHeight > viewport.scrollTop + viewport.clientHeight) viewport.scrollTop = row.offsetTop + row.offsetHeight - viewport.clientHeight;}, [active]);const close = () => { callbacks.current.onClose(); anchor.current?.focus({ preventScroll: true }); };- return createPortal(<div ref={panel} role="dialog" aria-label="Choose a model" className="fixed z-[200] flex flex-col overflow-hidden rounded-xl border border-line bg-surface shadow-overlay"+ return createPortal(<div ref={panel} role="dialog" aria-label="Choose a model" className="motion-surface fixed z-[200] flex flex-col overflow-hidden rounded-xl border border-line bg-surface shadow-overlay"style={{ ...position, visibility: position ? "visible" : "hidden" }} onKeyDown={event => {event.stopPropagation();if (event.key === "Escape") { event.preventDefault(); close(); }diff --git a/apps/native/components/primitives/PromptBar.tsx b/apps/native/components/primitives/PromptBar.tsxindex a84d6682..4917aa62 100644--- a/apps/native/components/primitives/PromptBar.tsx+++ b/apps/native/components/primitives/PromptBar.tsx@@ -112,7 +112,7 @@ export default function PromptBar({const menuAnchor = useRef<HTMLDivElement>(null);const menuPanel = useRef<HTMLDivElement>(null);const menuId = useId();- const { glimmRef, celebrate } = useComposerSweep();+ const { sweepRef, celebrate } = useComposerSweep();/* hand control to the user: stop the demo loop, and when they aim at* the input itself, clear the demo's leftover draft for a clean start */@@ -385,14 +385,13 @@ export default function PromptBar({event.target.value = "";}}/>- {/* rainbow glimm sweep — plays across the interior on model change.- explicit w/h: a <canvas> is a replaced element and won't stretch- to inset-0 alone, which feeds back into the shader's ResizeObserver. */}- <canvas- ref={glimmRef}+ {/* A brief accent sweep, released as soon as the model feedback ends. */}+ <span+ ref={sweepRef}aria-hidden="true"- className="pointer-events-none absolute inset-0 -z-10 h-full w-full"- style={{ borderRadius: "inherit" }}+ data-composer-sweep+ className="pointer-events-none absolute inset-0 -z-10 opacity-0"+ style={{ background: "linear-gradient(110deg, transparent 15%, color-mix(in srgb, var(--accent) 18%, transparent) 48%, transparent 80%)" }}/><spanref={measureRef}diff --git a/apps/native/components/primitives/ThinkingState.tsx b/apps/native/components/primitives/ThinkingState.tsxindex 56a8f10f..0936053f 100644--- a/apps/native/components/primitives/ThinkingState.tsx+++ b/apps/native/components/primitives/ThinkingState.tsx@@ -257,21 +257,21 @@ export default function ThinkingState({<path d="M20 6L9 17l-5-5" /></svg>) : (- <span className="size-3 shrink-0 rounded-full border-[1.5px] border-line-strong border-t-ink-2" style={{ animation: "spin 700ms linear infinite" }} />+ <span className="size-3 shrink-0 rounded-full border-[1.5px] border-line-strong border-t-ink-2" style={{ animation: expanded ? "spin 700ms linear infinite" : undefined }} />))}{row.shimmer ? (<><spanclassName="size-3 shrink-0 rounded-full border-[1.5px] border-line-strong border-t-ink-2"- style={{ animation: "spin 700ms linear infinite" }}+ style={{ animation: working && expanded ? "spin 700ms linear infinite" : undefined }}/><spanclassName="min-w-0 truncate bg-clip-text text-[12.5px] leading-relaxed text-transparent"style={{backgroundImage: "linear-gradient(90deg, var(--ink-3) 35%, var(--ink) 50%, var(--ink-3) 65%)",backgroundSize: "200% 100%",- animation: "shimmer-text 1.4s linear infinite",+ animation: working && expanded ? "shimmer-text 1.4s linear infinite" : undefined,}}>{row.primary}@@ -296,7 +296,7 @@ export default function ThinkingState({</>);const rowClass = "flex min-h-7 w-full items-center gap-2 rounded-[6px] px-1.5 py-0.5 text-left";- const key = `${i}:${row.primary}`;+ const key = live ? i : `${i}:${row.primary}`;const animation =i >= firstNewRow? { animation: `fade-up 320ms cubic-bezier(0.23,1,0.32,1) ${live ? 0 : i * 120}ms both` }diff --git a/apps/native/components/primitives/useComposerSweep.ts b/apps/native/components/primitives/useComposerSweep.tsindex 64c31b13..669dffb5 100644--- a/apps/native/components/primitives/useComposerSweep.ts+++ b/apps/native/components/primitives/useComposerSweep.ts@@ -1,22 +1,38 @@"use client";import { useEffect, useRef } from "react";-import { createShader, playSweep, accentChain, ACCENTS } from "glimm";-const RAINBOW = accentChain([ACCENTS.red, ACCENTS.orange, ACCENTS.yellow, ACCENTS.green, ACCENTS.cyan, ACCENTS.blue, ACCENTS.purple]);-/** Allocate a GPU context only while the optional model celebration is visible. */+/** One short compositor sweep; no canvas, render loop or retained GPU context. */export function useComposerSweep() {- const glimmRef = useRef<HTMLCanvasElement>(null);- const shaderRef = useRef<ReturnType<typeof createShader> | null>(null);- useEffect(() => () => { shaderRef.current?.destroy(); shaderRef.current = null; }, []);+ const sweepRef = useRef<HTMLSpanElement>(null);+ const animationRef = useRef<Animation | null>(null);+ const cancel = () => {+ const animation = animationRef.current;+ animationRef.current = null;+ if (animation) { animation.onfinish = null; animation.cancel(); }+ };+ useEffect(() => {+ const reduced = window.matchMedia("(prefers-reduced-motion: reduce)");+ const stopIfUnavailable = () => { if (document.hidden || reduced.matches) cancel(); };+ document.addEventListener("visibilitychange", stopIfUnavailable);+ reduced.addEventListener("change", stopIfUnavailable);+ return () => {+ document.removeEventListener("visibilitychange", stopIfUnavailable);+ reduced.removeEventListener("change", stopIfUnavailable);+ cancel();+ };+ }, []);const celebrate = () => {- if (shaderRef.current || !glimmRef.current || window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;- const shader = createShader({ canvas: glimmRef.current, palette: RAINBOW, direction: "ltr", bandTight: 10, swellAmount: 0.85 });- if (!shader) return;- shaderRef.current = shader;- const sweep = playSweep(shader, { palette: RAINBOW, direction: "ltr", sweepMs: 570, outroMs: 80,- peakAlpha: 1.3, bandTight: 10, brightness: 1.4, swellAmount: 1, waveSpeed: 1.8, easing: "easeOutExpo" });- const finish = () => { if (shaderRef.current === shader) { shader.destroy(); shaderRef.current = null; } };- void sweep.done.then(finish, finish);+ cancel();+ const element = sweepRef.current;+ if (!element || !element.animate || document.hidden || window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;+ const animation = element.animate([+ { transform: "translateX(-105%)", opacity: 0 },+ { transform: "translateX(-45%)", opacity: 0.8, offset: 0.2 },+ { transform: "translateX(55%)", opacity: 0.55, offset: 0.8 },+ { transform: "translateX(105%)", opacity: 0 },+ ], { duration: 480, easing: "cubic-bezier(0.22, 1, 0.36, 1)" });+ animationRef.current = animation;+ animation.onfinish = () => { if (animationRef.current === animation) cancel(); };};- return { glimmRef, celebrate };+ return { sweepRef, celebrate };}diff --git a/apps/native/components/site/ChatBubbles.tsx b/apps/native/components/site/ChatBubbles.tsxindex 4af0323a..e9d387e6 100644--- a/apps/native/components/site/ChatBubbles.tsx+++ b/apps/native/components/site/ChatBubbles.tsx@@ -10,26 +10,7 @@ import McpAppResult from "./McpAppResult";import SnapshotView from "./SnapshotView";import { pinScrollerTail } from "@/lib/follow-scroll";import { turnBlocks, type AssistantTurn } from "@/lib/acp";-import { createSmoothStream } from "@/lib/smooth-stream";--/** Typewriter reveal over the ACP text. Catch-up lands on whitespace so- * markdown chips/lists don't reflow every mid-token character. */-function useSmoothStream(target: string, live: boolean): string {- const [shown, setShown] = useState(target);- const stream = useRef<ReturnType<typeof createSmoothStream> | null>(null);- useEffect(() => {- if (!live) return;- stream.current = createSmoothStream(target, setShown);- return () => { stream.current?.dispose(); stream.current = null; };- // The controller owns subsequent targets without restarting its frame.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [live]);- useEffect(() => {- if (live) stream.current?.update(target, true);- else setShown(target);- }, [target, live]);- return live && target.startsWith(shown) ? shown : target;-}+import { useSmoothStream } from "./useSmoothStream";/** Reveal updates belong to this text block, not the entire tool/reasoning tree. */const StreamingMarkdown = memo(function StreamingMarkdown({ text, live, onOpenPath, scroller, following }: {diff --git a/apps/native/components/site/ChatEmpty.tsx b/apps/native/components/site/ChatEmpty.tsxindex dd53aa39..7f5c60b5 100644--- a/apps/native/components/site/ChatEmpty.tsx+++ b/apps/native/components/site/ChatEmpty.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useState, type CSSProperties } from "react";+import { useState } from "react";import PromptBar, { type PromptModel } from "@/components/primitives/PromptBar";import type { AcpCommand } from "@/lib/acp";import { STARTER_PROMPTS, type Health } from "@/lib/acp-client";@@ -14,24 +14,6 @@ function greeting(): string {return "Good evening";}-const HOME_REVEAL = {- offsetY: 23,- blur: 17,- duration: 800,- easing: "cubic-bezier(0.16, 1, 0.3, 1)",-};--function homeRevealStyle(visible: boolean): CSSProperties {- return {- opacity: visible ? 1 : 0,- transform: visible ? "translate3d(0, 0, 0)" : `translate3d(0, ${HOME_REVEAL.offsetY}px, 0)`,- filter: visible ? "blur(0px)" : `blur(${HOME_REVEAL.blur}px)`,- transition: ["opacity", "transform", "filter"]- .map((property) => `${property} ${HOME_REVEAL.duration}ms ${HOME_REVEAL.easing}`)- .join(", "),- };-}-export default function EmptyState({onSend, onSetting,health,@@ -64,24 +46,14 @@ export default function EmptyState({const [offset, setOffset] = useState(0);const shown = [0, 1, 2].map((i) => STARTER_PROMPTS[(offset + i) % STARTER_PROMPTS.length]);const shuffle = () => setOffset((current) => (current + 3) % STARTER_PROMPTS.length);- const [stage, setStage] = useState(0);- useEffect(() => {- const timers = [- setTimeout(() => setStage(1), 170),- setTimeout(() => setStage(2), 330),- setTimeout(() => setStage(3), 400),- setTimeout(() => setStage(4), 550),- ];- return () => timers.forEach(clearTimeout);- }, []);return (<div className={`mx-auto flex min-h-full w-full min-w-0 max-w-[720px] flex-col justify-center px-4 ${compact ? "py-2" : "py-10 sm:px-8"}`}>{!compact && <h1 className="text-[26px] font-normal tracking-[-0.02em] text-ink">- <span className="home-reveal block text-ink-3" style={homeRevealStyle(stage >= 1)}>+ <span className="home-reveal block text-ink-3">{greeting()}</span>- <span className="home-reveal block" style={homeRevealStyle(stage >= 2)}>+ <span className="home-reveal home-reveal-title block">What should graff work on?</span></h1>}@@ -96,7 +68,7 @@ export default function EmptyState({</div></div>}- <div className={`relative ${compact ? "" : "home-reveal mt-7"}`} style={compact ? undefined : homeRevealStyle(stage >= 3)}>+ <div className={`relative ${compact ? "" : "home-reveal home-reveal-composer mt-7"}`}><PromptBardemo={false}tall={!compact}@@ -119,7 +91,7 @@ export default function EmptyState({)}</div>- {!compact && <div className="home-reveal mt-6 flex flex-col" style={homeRevealStyle(stage >= 4)}>+ {!compact && <div className="home-reveal home-reveal-suggestions mt-6 flex flex-col">{shown.map((item) => (<buttonkey={item.id}diff --git a/apps/native/components/site/MotionLifecycle.tsx b/apps/native/components/site/MotionLifecycle.tsxnew file mode 100644index 00000000..ee0bdb8a--- /dev/null+++ b/apps/native/components/site/MotionLifecycle.tsx@@ -0,0 +1,16 @@+"use client";+import { useEffect } from "react";++/** Suspend CSS activity indicators when Chromium hides the document. */+export function MotionLifecycle() {+ useEffect(() => {+ const sync = () => { document.documentElement.dataset.motionHidden = String(document.hidden); };+ sync();+ document.addEventListener("visibilitychange", sync);+ return () => {+ document.removeEventListener("visibilitychange", sync);+ delete document.documentElement.dataset.motionHidden;+ };+ }, []);+ return null;+}diff --git a/apps/native/components/site/useSmoothStream.ts b/apps/native/components/site/useSmoothStream.tsnew file mode 100644index 00000000..38af0a4f--- /dev/null+++ b/apps/native/components/site/useSmoothStream.ts@@ -0,0 +1,39 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { createSmoothStream } from "@/lib/smooth-stream";++/** Reveal live text only while visible and motion is welcome. Switching either+ * condition off flushes the latest text and cancels the pending frame. */+export function useSmoothStream(target: string, live: boolean): string {+ const [shown, setShown] = useState(target);+ const latest = useRef(target);+ latest.current = target;+ const animated = useRef(false);+ const stream = useRef<ReturnType<typeof createSmoothStream> | null>(null);+ useEffect(() => {+ if (!live) return;+ const controller = createSmoothStream(latest.current, setShown);+ setShown(latest.current);+ const reduced = window.matchMedia("(prefers-reduced-motion: reduce)");+ const syncMotion = () => {+ animated.current = !document.hidden && !reduced.matches;+ controller.update(latest.current, animated.current);+ };+ stream.current = controller;+ syncMotion();+ document.addEventListener("visibilitychange", syncMotion);+ reduced.addEventListener("change", syncMotion);+ return () => {+ document.removeEventListener("visibilitychange", syncMotion);+ reduced.removeEventListener("change", syncMotion);+ controller.dispose();+ stream.current = null;+ };+ }, [live]);+ useEffect(() => {+ if (live) stream.current?.update(target, animated.current);+ else setShown(target);+ }, [target, live]);+ return live && target.startsWith(shown) ? shown : target;+}diff --git a/apps/native/electron/VISUAL-TESTS.md b/apps/native/electron/VISUAL-TESTS.mdindex d192f2f4..8cf56f3c 100644--- a/apps/native/electron/VISUAL-TESTS.md+++ b/apps/native/electron/VISUAL-TESTS.md@@ -275,3 +275,23 @@ the content budget, and verifies that revealing older history keeps newer replieand the reading anchor. `bun run test:browser-resources` opens local fixture pagesthrough the real BrowserTabs implementation, checks the live-view cap and release,and accelerates only the suspension grace period. Both have external watchdogs.++## Motion preview and lifecycle checks++After building the app, run the motion checks from `apps/native`:++```sh+node scripts/test-motion.mjs+```++The motion runner uses headless Chromium with synthetic responses and does not+open a desktop window or take mouse or keyboard focus. It exercises the actual+welcome screen, sidebar highlights, composer menus and model feedback without+starting an agent. It checks keyboard focus within the page, repeated interactions,+reduced motion, motion lifecycle handling and settled animations. Screenshots,+a recording when available, and results stay in the local motion output directory.+Headless visibility checks exercise page lifecycle handlers; they do not validate+macOS window occlusion or presented frames.++Compare resource use with the same production benchmark described above; motion+checks verify behavior and cleanup, not an overall desktop memory budget.diff --git a/apps/native/electron/motion-fixture.cjs b/apps/native/electron/motion-fixture.cjsnew file mode 100644index 00000000..0fc2f1e9--- /dev/null+++ b/apps/native/electron/motion-fixture.cjs@@ -0,0 +1,30 @@+// Synthetic data for headless motion checks.+function installMotionFixture() {+ const fallback = window.fetch;+ const models = ['Graff', 'Studio', 'sprinkles-5'];+ const catalog = { result: {+ current: { model: 'Graff', provider: '', effort: 'medium', fast: false, effortLevels: ['low', 'medium', 'high'] },+ models: models.map(name => ({ name, provider: '', context: 128000, authenticated: true, cost: 'local', current: name === 'Graff' })),+ commands: [{ name: 'help', description: 'Explore available commands' }, { name: 'compact', description: 'Summarize the conversation' }, { name: 'review', description: 'Review workspace changes' }],+ } };+ window.fetch = async (input, options) => {+ const url = new URL(typeof input === 'string' ? input : input.url, location.origin);+ const body = options?.body && typeof options.body === 'string' ? JSON.parse(options.body) : null;+ if (url.pathname === '/api/models' || (url.pathname === '/api/acp' && body?.method === 'graff/models')) {+ return new Response(JSON.stringify(catalog), { headers: { 'content-type': 'application/json' } });+ }+ if (url.pathname === '/api/acp' && body?.method === 'bootstrap') {+ return new Response(JSON.stringify({ sessionId: 'demo', commands: catalog.result.commands }), { headers: { 'content-type': 'application/json' } });+ }+ if (url.pathname === '/api/acp' && body?.method === 'session/prompt' && window.motionControlledStream) {+ return new Response(new ReadableStream({ start(controller) {+ const send = value => controller.enqueue(new TextEncoder().encode(JSON.stringify(value) + '\n'));+ window.motionStreamChunk = (text, thought = false) => send({ jsonrpc: '2.0', method: 'session/update', params: { sessionId: 'demo',+ update: { sessionUpdate: thought ? 'agent_thought_chunk' : 'agent_message_chunk', content: { type: 'text', text } } } });+ window.motionStreamFinish = () => { send({ jsonrpc: '2.0', id: 1, result: { stopReason: 'end_turn' } }); controller.close(); };+ } }), { headers: { 'content-type': 'application/x-ndjson' } });+ }+ return fallback(input, options);+ };+}+module.exports = { installMotionFixture };diff --git a/apps/native/lib/smooth-stream.test.ts b/apps/native/lib/smooth-stream.test.tsindex 382c83b2..9fc0dc6c 100644--- a/apps/native/lib/smooth-stream.test.ts+++ b/apps/native/lib/smooth-stream.test.ts@@ -43,3 +43,27 @@ test("reveal never publishes broken Unicode and disposal stops pending callbacksstream.dispose(); frames.at(-1)?.(200); stream.update("late", false);expect(painted.length).toBe(count);});++test("disabling motion flushes queued text and resuming only reveals future updates", () => {+ const { stream, frames, painted, tick } = fixture();+ const first = "A live answer with queued words. ".repeat(30);+ stream.update(first, true); tick(0);+ const pending = frames.length;+ stream.update(first, false);+ expect(painted.at(-1)).toBe(first);+ frames.at(-1)?.(30);+ expect(painted.at(-1)).toBe(first);+ const latest = `${first}Content received while motion is off. `;+ stream.update(latest, false);+ expect(painted.at(-1)).toBe(latest);+ expect(frames.length).toBe(pending);+ stream.update(latest, true);+ expect(frames.length).toBe(pending);+ const next = `${latest}Only this new content needs a reveal. `.repeat(2);+ stream.update(next, true);+ expect(frames.length).toBe(pending + 1);+ tick(pending);+ expect(painted.at(-1)?.startsWith(latest)).toBe(true);+ expect(painted.at(-1)?.length).toBeGreaterThan(latest.length);+ stream.dispose();+});diff --git a/apps/native/lib/smooth-stream.ts b/apps/native/lib/smooth-stream.tsindex 956d82a6..80f0d8d7 100644--- a/apps/native/lib/smooth-stream.ts+++ b/apps/native/lib/smooth-stream.ts@@ -37,10 +37,10 @@ export function createSmoothStream(initial: string, paint: (text: string) => voi});};return {- update(next: string, live: boolean) {+ update(next: string, animated: boolean) {if (closed) return;target = next;- if (!live || !target.startsWith(shown)) {+ if (!animated || !target.startsWith(shown)) {cancel();if (shown !== target) { shown = target; paint(shown); }return;diff --git a/apps/native/scripts/test-motion.mjs b/apps/native/scripts/test-motion.mjsnew file mode 100644index 00000000..1d6ac8c7--- /dev/null+++ b/apps/native/scripts/test-motion.mjs@@ -0,0 +1,274 @@+// Headless production motion checks. Never opens or focuses a native window.+// Usage: node scripts/test-motion.mjs /absolute/app/root /absolute/output+import { spawn } from 'node:child_process';+import fs from 'node:fs';+import path from 'node:path';+import os from 'node:os';+import net from 'node:net';+import assert from 'node:assert/strict';+import { createRequire } from 'node:module';+import { fileURLToPath } from 'node:url';+const require = createRequire(import.meta.url);+const { chromium } = require('@playwright/test');+const { installGalleryFixture } = require('../electron/gallery-fixture.cjs');+const { installMotionFixture } = require('../electron/motion-fixture.cjs');+const root = path.resolve(process.argv[2] || path.join(path.dirname(fileURLToPath(import.meta.url)), '..'));+const output = path.resolve(process.argv[3] || path.join(root, '../../zig-out/motion/current'));+const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));+let server, browser, context, page, video, complete = false, finishing = false;+assert.ok(fs.existsSync(chromium.executablePath()), 'Install the Playwright Chromium runtime before running headless checks');+const deadline = setTimeout(() => { console.error('Headless motion checks exceeded 120 seconds'); void finish(1); }, 120000);++try {+ fs.mkdirSync(output, { recursive: true });+ assert.ok(fs.existsSync(path.join(root, '.next/BUILD_ID')), 'Build the selected app first');+ const socket = net.createServer();+ await new Promise(resolve => socket.listen(0, '127.0.0.1', resolve));+ const port = socket.address().port;+ await new Promise(resolve => socket.close(resolve));+ const origin = `http://127.0.0.1:${port}`;+ const log = fs.openSync(path.join(output, 'motion-headless-server.log'), 'w');+ server = spawn(process.env.GRAFF_TEST_BUN || 'bun', ['node_modules/next/dist/bin/next', 'start', '--port', String(port), '--hostname', '127.0.0.1'], {+ cwd: root, env: { ...process.env, GRAFF_VISUAL_TESTS: '1', GRAFF_DESKTOP_TOKEN: '', NEXT_TELEMETRY_DISABLED: '1' }, detached: true, stdio: ['ignore', log, log],+ });+ fs.closeSync(log);+ for (let i = 0; i < 200; i++) {+ try { if ((await fetch(origin, { signal: AbortSignal.timeout(1000) })).ok) break; } catch {}+ if (i === 199) throw Error('Motion server did not start');+ await sleep(100);+ }+ browser = await chromium.launch({ headless: true });+ const ffmpegRoot = path.join(os.homedir(), 'Library/Caches/ms-playwright');+ const videoAvailable = fs.existsSync(ffmpegRoot) && fs.readdirSync(ffmpegRoot).some(name => name.startsWith('ffmpeg-'));+ context = await browser.newContext({ viewport: { width: 1440, height: 920 }, reducedMotion: 'no-preference',+ ...(videoAvailable ? { recordVideo: { dir: output, size: { width: 1440, height: 920 } } } : {}) });+ await context.addInitScript({ content: `(${installGalleryFixture.toString()})();(${installMotionFixture.toString()})();+ window.graffDesktop={projects:async()=>null,updates:async()=>({status:'unavailable',currentVersion:'1.0.0'}),browser:async()=>null,activity:async()=>null,terminal:async()=>null,windowControl:async()=>null,updateSubscribe:()=>()=>{},subscribe:()=>()=>{},terminalSubscribe:()=>()=>{}};` });+ const unexpected = [];+ await context.route('**/*', route => {+ const url = new URL(route.request().url());+ const allowed = url.origin === origin && !url.pathname.startsWith('/api/') || url.protocol === 'data:';+ if (!allowed) unexpected.push(url.origin === origin ? url.pathname : 'external request');+ return allowed ? route.continue() : route.abort();+ });+ page = await context.newPage();+ video = page.video();+ const cdp = await context.newCDPSession(page);+ await cdp.send('Performance.enable');+ const js = code => page.evaluate(code);+ const wait = expression => page.waitForFunction(expression, null, { timeout: 10000 });+ const metrics = async () => Object.fromEntries((await cdp.send('Performance.getMetrics')).metrics.map(({ name, value }) => [name, value]));+ const move = selector => page.locator(selector).hover();+ const click = selector => page.locator(selector).click();+ const key = name => page.keyboard.press(name);+ const draft = value => page.locator('textarea[aria-label="Prompt"]').fill(value);+ const running = () => js(`document.getAnimations().filter(a=>a.playState==='running'||a.pending).map(a=>({name:a.animationName??a.transitionProperty??'web-animation',target:a.effect?.target?.tagName}))`);+ const capture = async name => {+ await js('document.activeElement?.blur()');+ await sleep(300);+ await page.screenshot({ path: path.join(output, name) });+ };+ const visibility = hidden => page.evaluate(value => {+ Object.defineProperty(document, 'hidden', { configurable: true, value });+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: value ? 'hidden' : 'visible' });+ document.dispatchEvent(new Event('visibilitychange'));+ }, hidden);+ const report = { build: fs.readFileSync(path.join(root, '.next/BUILD_ID'), 'utf8').trim(),+ runtime: { chromium: browser.version(), headless: true }, checks: [],+ note: 'Headless Chromium, production build, fresh context, synthetic API responses and blocked API/network escape. Visibility checks dispatch synthetic document events; they do not verify native window throttling. Layout counters are observations, not a tight timing threshold.' };+ const passed = name => { report.checks.push(name); console.log('Motion:', name); };+ await page.goto(origin);+ await wait(`!!document.querySelector('textarea[aria-label="Prompt"]') && document.querySelector('[aria-label="Choose model"]')?.textContent.includes('Graff')`);+ await js(`window.motionEvents=[];for(const type of ['keydown','mouseover','focusin'])document.addEventListener(type,event=>{window.motionEvents.push({type,key:event.key,row:event.target.closest?.('[data-motion-row]')?.dataset.motionRow,label:event.target.getAttribute?.('aria-label')});if(window.motionEvents.length>30)window.motionEvents.shift()},true)`);+ await js('document.fonts.ready.then(()=>true)');+ await sleep(1100);+ assert.deepEqual(await running(), [], 'The settled home screen must not animate indefinitely');+ assert.ok(await js(`document.querySelectorAll('.home-reveal').length>=3`), 'The fixture must show the home entrance content');+ assert.equal(await js(`document.querySelectorAll('[data-promptbar] canvas').length`), 0, 'The composer must not retain a canvas');+ assert.ok(await js(`[...document.querySelectorAll('.home-reveal')].every(e=>{const s=getComputedStyle(e);return s.opacity==='1'&&s.filter==='none'&&s.willChange==='auto'})`), 'Home reveal must settle without a blur or permanent will-change');+ passed('home settles with no running animations, blur or composer canvas');+ await capture('motion-home.png');++ const sidebar = '[aria-label="Workspace navigation"]';+ const rowSelector = `${sidebar} button[data-row]`;+ const rows = await js(`document.querySelectorAll(${JSON.stringify(rowSelector)}).length`);+ assert.ok(rows >= 4, 'The fixture must expose multiple real sidebar rows');+ // Tag existing controls for stable input targets without changing their styling.+ await js(`[...document.querySelectorAll(${JSON.stringify(rowSelector)})].forEach((e,i)=>e.dataset.motionRow=String(i))`);+ const target = index => `[data-motion-row="${index}"]`;+ const aligned = index => js(`(()=>{const row=document.querySelector(${JSON.stringify(target(index))});const group=row.closest('[class~="group/glide-menu"]');const h=group.querySelector(':scope > span[aria-hidden]');const a=h.getBoundingClientRect(),b=row.getBoundingClientRect();return Math.abs(a.top-b.top)<1&&Math.abs(a.height-b.height)<1&&getComputedStyle(h).opacity==='1'})()`);+ await move(target(0)); await sleep(280);+ const before = await metrics();+ for (let index = 0; index < 24; index++) { await move(target(index % 4)); await sleep(24); }+ await sleep(300);+ const after = await metrics();+ report.hover = { moves: 24, layoutCount: after.LayoutCount - before.LayoutCount,+ layoutMs: 1000 * (after.LayoutDuration - before.LayoutDuration), styleMs: 1000 * (after.RecalcStyleDuration - before.RecalcStyleDuration) };+ assert.ok(await aligned(3), 'Pointer highlight must finish on the last hovered row');+ await move('h1'); await sleep(160);+ await js(`document.querySelector(${JSON.stringify(target(1))}).focus()`);+ await key('Tab'); await sleep(280);+ assert.equal(await js('document.activeElement.dataset.motionRow'), '2', 'Tab must advance to the next sidebar row');+ assert.ok(await aligned(2), 'Keyboard focus must move the shared highlight');+ await move(`${target(0)} svg`); await sleep(280);+ await js(`document.querySelector(${JSON.stringify(target(2))}).focus()`); await sleep(280);+ await move(`${target(0)} .sidebar-copy`); await sleep(280);+ assert.ok(await aligned(0), 'Returning to another child of the hovered row must reclaim the highlight after keyboard focus');+ passed('rapid browser pointer input and keyboard focus settle on the correct sidebar row');++ const modelDialog = '[aria-label="Choose a model"]';+ const modelOptions = '[aria-label="Available models"] [role="option"]';+ for (let repeat = 0; repeat < 2; repeat++) {+ await click('[aria-label="Choose model"]');+ await wait(`document.activeElement?.getAttribute('aria-label')==='Filter models'`);+ await sleep(200);+ await move(`${modelOptions}:nth-child(2)`);+ await wait(`document.querySelector('[aria-label="Filter models"]').getAttribute('aria-activedescendant')===document.querySelector(${JSON.stringify(`${modelOptions}:nth-child(2)`)}).id`);+ await key('ArrowDown');+ await wait(`document.querySelector('[aria-label="Filter models"]').getAttribute('aria-activedescendant')===document.querySelector(${JSON.stringify(`${modelOptions}:nth-child(3)`)}).id`);+ if (repeat === 0) await capture('motion-model-menu.png');+ // capture blurs the field; restore focus so Escape follows the dialog path.+ await js(`document.querySelector('[aria-label="Filter models"]').focus()`);+ await key('Escape');+ await wait(`!document.querySelector(${JSON.stringify(modelDialog)})`);+ assert.equal(await js('document.activeElement.getAttribute("aria-label")'), 'Choose model');+ }+ passed('model menu pointer and keyboard selection, focus restoration, Escape and reopening');++ for (let repeat = 0; repeat < 2; repeat++) {+ await draft('/');+ await wait(`document.querySelectorAll('[data-composer-menu] [role="option"]').length>1`);+ await key('ArrowDown');+ await wait(`document.querySelector('[data-composer-menu] [role="option"]:nth-child(2)').getAttribute('aria-selected')==='true'`);+ await move('[data-composer-menu] [role="option"]:first-child');+ await wait(`document.querySelector('[data-composer-menu] [role="option"]').getAttribute('aria-selected')==='true'`);+ await key('Escape');+ await wait(`!document.querySelector('[data-composer-menu]')`);+ assert.equal(await js('document.activeElement.getAttribute("aria-label")'), 'Prompt');+ await draft('');+ }+ passed('composer menu pointer and keyboard selection, retained focus, Escape and reopening');+ for (let repeat = 0; repeat < 2; repeat++) {+ await click('[aria-label="Select effort"]');+ await wait(`!!document.querySelector('[aria-label="Reasoning effort"]')`);+ await key('Escape');+ await wait(`!document.querySelector('[aria-label="Reasoning effort"]')`);+ assert.equal(await js('document.activeElement.getAttribute("aria-label")'), 'Choose model');+ }+ passed('effort menu Escape, focus restoration and reopening');++ // Extend a production entrance to test the visibility listener and CSS gate.+ // Headless documents cannot reproduce native minimize/occlusion behavior.+ await click('[aria-label="Choose model"]');+ await wait(`!!document.querySelector(${JSON.stringify(modelDialog)})`);+ await js(`document.querySelector(${JSON.stringify(modelDialog)}).style.animationDuration='10s'`);+ assert.notEqual(await js(`getComputedStyle(document.querySelector(${JSON.stringify(modelDialog)})).animationName`), 'none');+ await sleep(250);+ await visibility(true);+ await wait(`document.hidden && document.documentElement.dataset.motionHidden==='true'`);+ assert.equal(await js(`getComputedStyle(document.querySelector(${JSON.stringify(modelDialog)})).animationPlayState`), 'paused');+ await wait(`document.querySelector(${JSON.stringify(modelDialog)}).getAnimations().every(a=>!a.pending)`);+ assert.deepEqual(await running(), [], 'Hidden windows must pause CSS motion');+ await visibility(false);+ await wait(`!document.hidden && document.documentElement.dataset.motionHidden!=='true'`);+ assert.equal(await js(`getComputedStyle(document.querySelector(${JSON.stringify(modelDialog)})).animationPlayState`), 'running');+ await js(`document.querySelector('[aria-label="Filter models"]').focus()`); await key('Escape');+ await wait(`!document.querySelector(${JSON.stringify(modelDialog)})`);+ passed('synthetic visibility events pause CSS motion and resume it');++ const celebrate = async () => {+ await click('[aria-label="Choose model"]');+ await wait(`!!document.querySelector(${JSON.stringify(modelDialog)})`);+ const started = await js(`(()=>{[...document.querySelectorAll(${JSON.stringify(modelOptions)})].find(e=>e.textContent.includes('sprinkles-5')).click();return document.querySelector('[data-composer-sweep]').getAnimations().length>0})()`);+ await wait(`!document.querySelector(${JSON.stringify(modelDialog)})`);+ return started;+ };+ assert.ok(await celebrate(), 'Selecting the special fixture model must start its feedback animation');+ await sleep(700);+ assert.equal(await js(`document.querySelector('[data-composer-sweep]').getAnimations().length`), 0, 'Finished feedback must release its animation');+ assert.equal(await js(`getComputedStyle(document.querySelector('[data-composer-sweep]')).opacity`), '0');+ passed('composer feedback finishes and releases its animation');++ await cdp.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-reduced-motion', value: 'reduce' }] });+ await page.goto(origin);+ await wait(`!!document.querySelector('textarea[aria-label="Prompt"]') && document.querySelector('[aria-label="Choose model"]')?.textContent.includes('Graff')`);+ assert.ok(await js(`document.querySelectorAll('.home-reveal').length>=3`));+ assert.ok(await js(`[...document.querySelectorAll('.home-reveal')].every(e=>{const s=getComputedStyle(e);return s.opacity==='1'&&s.animationName==='none'&&s.animationDelay==='0s'})`), 'Reduced motion must reveal home without an entrance delay');+ await click('[aria-label="Choose model"]');+ await wait(`document.activeElement?.getAttribute('aria-label')==='Filter models'`);+ assert.ok(await js(`(()=>{const s=getComputedStyle(document.querySelector(${JSON.stringify(modelDialog)}));return s.opacity==='1'&&s.animationName==='none'})()`));+ await key('Escape'); await wait(`!document.querySelector(${JSON.stringify(modelDialog)})`);+ assert.equal(await celebrate(), false, 'Reduced motion must skip the feedback at invocation');+ assert.equal(await js(`document.querySelector('[data-composer-sweep]').getAnimations().length`), 0);+ assert.deepEqual(await running(), [], 'Reduced motion must disable decorative animation');+ passed('reduced motion reveals content immediately and skips menu and composer feedback animations');+ await cdp.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-reduced-motion', value: 'no-preference' }] });+ await page.goto(origin);+ await wait(`!!document.querySelector('textarea[aria-label="Prompt"]') && document.querySelector('[aria-label="Choose model"]')?.textContent.includes('Graff')`);+ await sleep(1100);+ await capture('motion-preview.png');++ await js('window.motionControlledStream=true');+ await draft('Show how the workspace stays responsive while a reply arrives.');+ await wait(`!document.querySelector('[aria-label="Send"]').disabled`);+ await click('[aria-label="Send"]');+ await wait(`typeof window.motionStreamChunk==='function'`);+ await js(`window.motionStreamChunk('Checking the motion lifecycle',true)`);+ await wait(`document.querySelector('article')?.textContent.includes('Checking the motion lifecycle')`);+ await js(`window.motionReasoningRow=[...document.querySelectorAll('article span')].find(e=>e.textContent==='Checking the motion lifecycle').parentElement;window.motionStreamChunk(' as the reply grows.',true)`);+ await wait(`document.querySelector('article')?.textContent.includes('as the reply grows.')`);+ assert.ok(await js(`window.motionReasoningRow.isConnected && window.motionReasoningRow.textContent.includes('as the reply grows.')`), 'A live reasoning update must reuse its row');+ await click('article button[aria-expanded="true"]');+ await sleep(450);+ assert.equal(await js(`document.querySelector('article button[aria-expanded]').nextElementSibling.getAnimations({subtree:true}).filter(a=>a.playState==='running').length`), 0, 'Collapsed reasoning rows must not animate');+ await js(`window.motionStreamChunk('The workspace is ready. ')`);+ await wait(`document.querySelector('article')?.textContent.includes('The workspace is ready.')`);+ await js(`window.motionStreamChunk('A calm interface keeps the conversation readable. '.repeat(100)+'REDUCED-FLUSH-MARKER')`);+ await sleep(100);+ assert.ok(await js(`!document.querySelector('article').textContent.includes('REDUCED-FLUSH-MARKER')`), 'The fixture must exercise an in-flight reveal');+ await cdp.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-reduced-motion', value: 'reduce' }] });+ // Let the media event and React commit cross a rendering boundary; do not+ // mistake an eventually completed typewriter for an immediate flush.+ await js(`new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve(true)))))`);+ assert.ok(await js(`document.querySelector('article').textContent.includes('REDUCED-FLUSH-MARKER')`), 'Reduced motion must flush at the next rendering boundary');+ await cdp.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-reduced-motion', value: 'no-preference' }] });+ await js(`window.motionStreamChunk(' New updates remain readable. '.repeat(100)+'HIDDEN-FLUSH-MARKER')`);+ await sleep(100);+ assert.ok(await js(`!document.querySelector('article').textContent.includes('HIDDEN-FLUSH-MARKER')`));+ await visibility(true);+ await wait(`document.hidden && document.querySelector('article').textContent.includes('HIDDEN-FLUSH-MARKER')`);+ await visibility(false);+ await wait('!document.hidden');+ await js('window.motionStreamFinish()');+ await wait(`document.querySelector('article')?.getAttribute('aria-busy')==='false'`);+ await sleep(700);+ assert.deepEqual(await running(), [], 'A completed reply and collapsed reasoning must not retain running animations');+ passed('streaming reasoning reuses rows; collapsed rows stop; reduced motion and hide flush pending text; completed reply settles');+ await js("window.dispatchEvent(new CustomEvent('graff-desktop-action',{detail:'close'}))");+ await wait(`!document.querySelector('article') && !!document.querySelector('textarea[aria-label="Prompt"]')`);+ await sleep(700);+ assert.deepEqual(unexpected, [], 'Motion checks must not call real APIs or external services');+ report.unexpectedRequests = unexpected;+ fs.writeFileSync(path.join(output, 'motion-headless-report.json'), JSON.stringify(report, null, 2));+ complete = true;+ console.log('Headless motion checks complete:', output);++} catch (error) {+ console.error(error);+ if (page && !page.isClosed()) {+ try { console.error('Page focus:', await page.evaluate(() => ({ label: document.activeElement?.getAttribute('aria-label'), tag: document.activeElement?.tagName }))); await page.screenshot({ path: path.join(output, 'motion-headless-failure.png') }); } catch {}+ }+} finally { await finish(complete ? 0 : 1); }++async function finish(code) {+ if (finishing) return;+ finishing = true;+ clearTimeout(deadline);+ if (context) await context.close().catch(() => {});+ if (video) {+ try { await video.saveAs(path.join(output, complete ? 'motion-preview.webm' : 'motion-headless-failure.webm')); await video.delete(); } catch {}+ }+ if (browser) await browser.close().catch(() => {});+ if (server?.pid) try { process.kill(-server.pid, 'SIGTERM'); } catch {}+ process.exitCode = code;+}