Compare commits

...
Author SHA1 Message Date
b35f3f8e26 perf(app): turn the status ring thirty times a second, not once per display frame
A window is composed and presented again every time something in it
moves. The ring on a running workspace turned with the display, so a
visible ring held the whole window at 60 or 120 frames a second for as
long as any agent ran, even while the chat on screen was idle. On macOS
that work lands in WindowServer; on Android in RenderThread.

The ring now takes 27 positions per 900 ms turn, which is 30 a second.
Each is a position the smooth turn passes through, 1.2 px apart on the
12 px ring. On web the keyframes use steps(27), and the compositor draws
a frame only when the step changes. On native the shared clock holds its
position at each step; a view whose transform did not change is not
invalidated, so nothing is drawn between steps.

The native clock starts on a frame and advances whole frames, so a step
that is a whole number of frames long would turn over exactly on a
frame, and rounding would pick the side. Each step turns over an eighth
of a step early, which is between two frames at 60, 90 and 120 Hz.

The tool-call shimmer still moves every frame, so a chat with a running
tool call in view draws at the display's rate as before.

Refs #5429, #7559, #3971

Co-authored-by: Wanno Drijfhout <git@wanno.eu>
Co-authored-by: luke <luopeihuan@gmail.com>
Co-authored-by: Daniel JB Clark <djbclark@gmail.com>
2026-11-30 17:03:51 +01:00
8 changed files with 268 additions and 16 deletions
+38 -6
View File
@@ -22,6 +22,31 @@ value.
Animate only `transform` and `opacity`. Anything else is painted on the main thread every frame.
## Frames
Keeping the animation off the React thread does not make it free. Every time an indicator moves,
the platform composes and presents the whole window again: `RenderThread` on Android, the GPU
process and macOS's WindowServer on desktop. An indicator that moves with the display holds the
window at 60 or 120 frames a second for as long as an agent runs, with nothing else changing.
So an indicator moves in steps, and the step count is its frame rate:
| Indicator | Positions | Frames a second |
| ----------------- | ----------------------------------- | --------------- |
| Loader | 6 per 950 ms | 6 |
| Status ring | 27 per 900 ms (`STATUS_RING_STEPS`) | 30 |
| Tool-call shimmer | every display frame | 60 or 120 |
The ring is the one that matters most: it is on screen in the sidebar and the tab bar whenever any
agent runs, including while you read an idle chat. Its steps are positions the smooth turn passes
through, 1.2 px apart on a 12 px ring. Fewer steps start to read as ticking and buy little: measured
on an Android emulator with one ring on screen, the app used 12–15% of a core with a smooth ring,
8–10% with 27 steps, and 6–7% with either 18 or 12, because the native driver's own tick is what is
left.
Two indicators only share frames when their steps turn over at the same instants. The shimmer still
moves every frame, so a chat with a running tool call in view draws at the display's rate.
## Web
`useIndicatorLoop` runs a keyframe loop through the Web Animations API (`element.animate`). The
@@ -41,8 +66,9 @@ Two more reasons the stylesheet route does not work here:
Indicators that must move together use `phase: "shared"`, which starts the loop at the document
timeline's origin instead of at mount. Every ring and every loader is then at the same point of its
cycle wherever and whenever it mounted. A stepped animation sets `easing: "step-end"` on each
keyframe; the compositor then draws a frame when a step changes and none in between.
cycle wherever and whenever it mounted. A stepped animation sets its easing on the keyframes:
`step-end` to hold each keyframe until the next, `steps(n)` to cross between two keyframes in `n`
even steps. The compositor then draws a frame when a step changes and none in between.
## Native
@@ -57,6 +83,9 @@ its value from the frame timestamp instead of replaying a 60 fps recording, so i
refresh rate and needs no loop restart. `Animated.modulo` and `interpolate` turn the clock into a
rotation or a translation, all inside the native driver.
`cycle(periodMs, steps)` holds the position at each step. The driver still ticks every frame, but a
view whose transform did not change is not invalidated, so nothing is drawn between steps.
The loader changes six times per cycle, so it does not ride the frame clock. `step-ticker.ts` wakes
the JS thread once per step, aligned to wall-clock step boundaries, and publishes the step into a
native `Animated.Value`. A wake-up that arrives late publishes the step that is current by then, so
@@ -69,7 +98,8 @@ Do not apply Unistyles dynamic styles to these `Animated.View`s; see
`e2e/browser/running-indicators.spec.ts` holds the web budgets: animation-frame callbacks, style
recalculations, paints and main-thread commits per second on a quiet running turn, React renders of
the indicator components, the loader's cadence, reduced motion, and a hidden tab. Run it with
the indicator components, the loader's and the ring's cadence, the frames a ring draws beside an
idle chat, reduced motion, and a hidden tab. Run it with
`PASEO_RUNNING_INDICATORS_FRAMES=1` to also save reference frames of every indicator at fixed
points of its cycle, for a pixel comparison across a change.
@@ -77,6 +107,8 @@ To hold a turn in the running state without streaming, send the mock load-test a
`Hold a running shell tool call for <N>ms`.
On Android, compare `adb shell dumpsys gfxinfo <package>` frame counts and per-thread CPU from
`/proc/<pid>/task/*/stat` over a fixed window. The UI thread (`sh.paseo.debug`) is the one a
regression shows up on; `RenderThread` draws 60 frames a second whenever a ring or a shimmer is on
screen, and that part is the cost of the motion itself.
`/proc/<pid>/task/*/stat` over a fixed window. A regression in how an indicator is driven shows up
on the UI thread (`sh.paseo.debug`); one in how often it moves shows up as frames rendered and on
`RenderThread`. `dumpsys gfxinfo <package> framestats` lists each frame's vsync, which shows whether
the steps are evenly spaced. On the emulator gfxinfo counts every frame that follows an idle vsync
as janky; read the frame count and the percentiles instead.
@@ -8,11 +8,13 @@ import {
import {
captureLoaderSteps,
freezeAnimationsAt,
openIdleChatBesideRunningAgent,
openQuietRunningTurn,
readAnimatingTargets,
readLoaderStep,
readRunningAnimations,
recordLoaderStepChanges,
recordRingAngles,
runningToolCall,
statusRings,
workingLoader,
@@ -45,6 +47,10 @@ const PAINTED_VIEWPORTS_PER_SECOND_BUDGET = 4;
const LOADER_PERIOD_MS = 950;
const LOADER_STEP_MS = LOADER_PERIOD_MS / 6;
const STATUS_RING_PERIOD_MS = 900;
const STATUS_RING_STEPS = 27;
// Thirty ring positions a second, plus the few frames a second the rest of the page draws. A ring
// that turns with the display draws sixty or more.
const RING_ONLY_FRAMES_PER_SECOND_BUDGET = 36;
// React renders these once when the indicator appears. Rendering again while the turn is quiet
// means the animation is being driven through React.
@@ -109,6 +115,45 @@ test.describe("Running indicators", () => {
}
});
test("a ring beside an idle chat redraws the window thirty times a second", async ({
page,
browser,
}, testInfo) => {
test.setTimeout(180_000);
const scene = await openIdleChatBesideRunningAgent(page);
try {
const animating = await readAnimatingTargets(page);
const activity = await measureSteadyStateActivity({
browser,
page,
windowMs: SAMPLE_WINDOW_MS,
});
const angles = await recordRingAngles(page, STATUS_RING_PERIOD_MS * 3);
await writeFile(
testInfo.outputPath("evidence.json"),
JSON.stringify({ animating, activity, angles }, null, 2),
);
// Nothing but rings is moving, so every frame drawn is a ring's.
expect.soft(new Set(animating)).toEqual(new Set(["status-ring"]));
expect
.soft(activity.compositorFramesPerSecond)
.toBeLessThan(RING_ONLY_FRAMES_PER_SECOND_BUDGET);
// The cadence is part of the design: the quarter is only ever at one of its even steps.
const stepDegrees = 360 / STATUS_RING_STEPS;
const offStep = angles.filter((angle) => {
const stepsAlong = angle / stepDegrees;
return Math.abs(stepsAlong - Math.round(stepsAlong)) * stepDegrees > 0.05;
});
expect.soft(offStep).toEqual([]);
expect.soft(angles.length).toBeGreaterThan(STATUS_RING_STEPS / 2);
expect.soft(angles.length).toBeLessThanOrEqual(STATUS_RING_STEPS);
} finally {
await scene.cleanup();
}
});
test("hold still when the system asks for reduced motion", async ({
page,
browser,
@@ -50,6 +50,76 @@ export async function openQuietRunningTurn(page: Page): Promise<MockAgentWorkspa
}
}
/**
* Opens an idle chat while an agent runs in another workspace: the only thing moving on screen is
* the running workspace's status ring in the sidebar.
*/
export async function openIdleChatBesideRunningAgent(page: Page): Promise<{
cleanup(): Promise<void>;
}> {
const running = await seedMockAgentWorkspace({
repoPrefix: "running-beside-",
title: "Running beside",
initialPrompt: HELD_TOOL_CALL_PROMPT,
});
try {
const idle = await seedMockAgentWorkspace({ repoPrefix: "idle-chat-", title: "Idle chat" });
const cleanup = async () => {
await idle.cleanup();
await running.cleanup();
};
try {
await openAgentRoute(page, { workspaceId: idle.workspaceId, agentId: idle.agentId });
await expectComposerVisible(page);
await expect(statusRings(page).first()).toBeVisible({ timeout: 30_000 });
await expect(workingLoader(page)).toHaveCount(0);
await page.mouse.move(900, 300);
return { cleanup };
} catch (error) {
await cleanup();
throw error;
}
} catch (error) {
await running.cleanup().catch(() => undefined);
throw error;
}
}
/** Every angle the first visible status ring's quarter is seen at over the window, in degrees. */
export async function recordRingAngles(page: Page, windowMs: number): Promise<number[]> {
return statusRings(page)
.first()
.evaluate(
(ring, sampleWindowMs) =>
new Promise<number[]>((resolve, reject) => {
const turning = document
.getAnimations()
.map((animation) => animation.effect)
.filter((effect): effect is KeyframeEffect => effect instanceof KeyframeEffect)
.find((effect) => effect.target && ring.contains(effect.target));
const quarter = turning?.target;
if (!quarter) {
reject(new Error("The status ring is not turning"));
return;
}
const angles = new Set<number>();
const startedAt = performance.now();
const sample = () => {
const { a, b } = new DOMMatrixReadOnly(getComputedStyle(quarter).transform);
const degrees = (Math.atan2(b, a) * 180) / Math.PI;
angles.add(Math.round(((degrees + 360) % 360) * 100) / 100);
if (performance.now() - startedAt >= sampleWindowMs) {
resolve([...angles].sort((first, second) => first - second));
return;
}
requestAnimationFrame(sample);
};
sample();
}),
windowMs,
);
}
/** The loader's current step, or null while the dots are between two readable states. */
export async function readLoaderStep(page: Page): Promise<number | null> {
const opacities = await loaderDots(page).evaluateAll((dots) =>
@@ -0,0 +1,79 @@
import { Animated } from "react-native";
import { describe, expect, test } from "vitest";
import { createIndicatorClock } from "./clock";
const PERIOD_MS = 900;
const STEPS = 27;
const STEP_MS = PERIOD_MS / STEPS;
// Animated only pushes a derived value to a mounted view, so this asks the node for it the way the
// view's props do.
function read(node: object): number {
if (!("__getValue" in node) || typeof node.__getValue !== "function") {
throw new Error("Not an Animated node");
}
return Number(node.__getValue());
}
// Where the cycle is at each of the given clock readings.
function positionsAt(elapsed: number[], steps?: number): number[] {
const elapsedMs = new Animated.Value(0);
const position = createIndicatorClock(elapsedMs).cycle(PERIOD_MS, steps);
return elapsed.map((ms) => {
elapsedMs.setValue(ms);
return Math.round(read(position) * 1e6) / 1e6;
});
}
// A display's frames, as the native driver's clock counts them: whole frames from zero.
function frames(hz: number, count: number): number[] {
return Array.from({ length: count }, (_, frame) => (frame * 1000) / hz);
}
describe("indicator clock", () => {
test("a cycle without steps advances with every frame", () => {
expect(positionsAt([0, 16, 450, 899, 900, 916])).toEqual([0, 16, 450, 899, 0, 16]);
});
test("a stepped cycle only ever sits on one of its even steps", () => {
const positions = positionsAt(frames(60, 3 * 54), STEPS);
expect(new Set(positions).size).toBe(STEPS);
for (const position of positions) {
expect(position / STEP_MS).toBeCloseTo(Math.round(position / STEP_MS), 4);
expect(position).toBeLessThan(PERIOD_MS);
}
});
test.each([60, 90, 120])("at %i Hz every step is held for the same number of frames", (hz) => {
const positions = positionsAt(frames(hz, hz * 3), STEPS);
const heldFor: number[] = [];
let run = 1;
for (let frame = 1; frame < positions.length; frame += 1) {
if (positions[frame] === positions[frame - 1]) {
run += 1;
} else {
heldFor.push(run);
run = 1;
}
}
// The first step is cut short by the lead; every step after it is whole.
expect(new Set(heldFor.slice(1))).toEqual(new Set([hz / 30]));
});
test("a frame that lands a hair early or late shows the same step", () => {
const onTime = positionsAt(frames(60, 120), STEPS);
const early = positionsAt(
frames(60, 120).map((ms) => ms - 0.2),
STEPS,
).slice(1);
const late = positionsAt(
frames(60, 120).map((ms) => ms + 0.2),
STEPS,
);
expect(early).toEqual(onTime.slice(1));
expect(late).toEqual(onTime);
});
});
@@ -7,6 +7,12 @@ import { Animated } from "react-native";
// rate and never ends or loops.
const CLOCK_CONFIG = { velocity: 1, deceleration: 1 - 1e-12, useNativeDriver: true };
// The clock starts on a frame and advances a whole frame at a time, so at 60, 90 and 120 Hz a step
// that is a whole number of frames long would turn over exactly on a frame, and rounding would
// decide frame by frame which side of the step it fell on. Turning each step over this fraction of
// a step early puts the turn between two frames at all three rates.
const STEP_LEAD = 1 / 8;
/**
* Milliseconds, counted on the UI thread by React Native's native animation driver.
*
@@ -15,20 +21,31 @@ const CLOCK_CONFIG = { velocity: 1, deceleration: 1 - 1e-12, useNativeDriver: tr
* on every frame it changes.
*/
export interface IndicatorClock {
/** Where a cycle of `periodMs` currently is, as milliseconds into the cycle. */
cycle(periodMs: number): Animated.AnimatedModulo<number>;
/**
* Where a cycle of `periodMs` currently is, as milliseconds into the cycle.
*
* With `steps`, the position holds at each of that many even steps instead of advancing every
* frame. A view bound to a held position is not redrawn until the step turns over.
*/
cycle(periodMs: number, steps?: number): Animated.AnimatedInterpolation<number>;
/** Runs the clock until the returned function is called. It restarts from zero when idle. */
run(): () => void;
}
export function createIndicatorClock(): IndicatorClock {
const elapsedMs = new Animated.Value(0, { useNativeDriver: true });
export function createIndicatorClock(
elapsedMs = new Animated.Value(0, { useNativeDriver: true }),
): IndicatorClock {
let runners = 0;
let ticking: Animated.CompositeAnimation | null = null;
return {
cycle(periodMs) {
return Animated.modulo(elapsedMs, periodMs);
cycle(periodMs, steps) {
if (!steps) {
return Animated.modulo(elapsedMs, periodMs);
}
const stepMs = periodMs / steps;
const position = Animated.modulo(Animated.add(elapsedMs, stepMs * STEP_LEAD), periodMs);
return Animated.subtract(position, Animated.modulo(position, stepMs));
},
run() {
runners += 1;
@@ -31,6 +31,12 @@ export const STATUS_RING_HEAD_OPACITY = 0.9;
// already turning.
export const STATUS_RING_PERIOD_MS = 900;
// The quarter takes thirty positions a second, not one per display refresh. A window is redrawn
// every time the ring moves, so a ring that moves with the display holds the whole window at the
// display's rate for as long as an agent runs. Each position is one the smooth turn passes through,
// 1.2 px further along a 12 px ring.
export const STATUS_RING_STEPS = 27;
/**
* Re-anchors a corner status dot's offset for the ring that replaces it.
*
@@ -8,11 +8,11 @@ import {
rotatorStyles,
styles,
} from "@/components/status-ring/frame";
import { STATUS_RING_PERIOD_MS } from "@/components/status-ring/geometry";
import { STATUS_RING_PERIOD_MS, STATUS_RING_STEPS } from "@/components/status-ring/geometry";
// One rotation for every ring in the app, so a row that appears mid-flight lands in step with the
// rings already turning.
const rotation = sharedIndicatorClock.cycle(STATUS_RING_PERIOD_MS).interpolate({
const rotation = sharedIndicatorClock.cycle(STATUS_RING_PERIOD_MS, STATUS_RING_STEPS).interpolate({
inputRange: [0, STATUS_RING_PERIOD_MS],
outputRange: ["0deg", "360deg"],
});
@@ -8,12 +8,15 @@ import {
rotatorStyles,
styles,
} from "@/components/status-ring/frame";
import { STATUS_RING_PERIOD_MS } from "@/components/status-ring/geometry";
import { STATUS_RING_PERIOD_MS, STATUS_RING_STEPS } from "@/components/status-ring/geometry";
// A sidebar full of agents can hold dozens of rings at once; the shared phase keeps them turning as
// one, and a row that appears mid-flight lands in step with the rings already turning.
const TURNING: IndicatorLoop = {
keyframes: [{ transform: "rotate(0deg)" }, { transform: "rotate(360deg)" }],
keyframes: [
{ transform: "rotate(0deg)", easing: `steps(${STATUS_RING_STEPS})` },
{ transform: "rotate(360deg)" },
],
durationMs: STATUS_RING_PERIOD_MS,
phase: "shared",
};