Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(interaction-harness): the recorder reads no run at its end in traces (#10730)

Christopher Chedeau833388f156ac
diff --git a/internal/interaction-harness/README.md b/internal/interaction-harness/README.md
index 749bc06052..529e9c9304 100644
--- a/internal/interaction-harness/README.md
+++ b/internal/interaction-harness/README.md
@@ -410,8 +410,10 @@ harness's own animation recorder stands down while the trace runs, since its
frame loop would make every frame a main-thread one, restyling each running
animation's target and laying out an anchored one: it reads only the element a
CSS animation or transition event names, once, when that animation starts, and
-catches up afterwards. The frame it requested before the trace runs before the
-start mark, so the whole window counts none of its work. A `waitForRest`
+catches up afterwards. A CSS run's end event reads nothing then either: the
+recorder keeps the end and dates the run once the trace ends. The frame it
+requested before the trace runs before the start mark, so the whole window
+counts none of its work. A `waitForRest`
awaited inside the traced body stands
down too: it waits on timers for the scheduled ends of the element's curves
(looking `frames` times a frame apart before settling on none, so an
diff --git a/internal/interaction-harness/src/curves.ts b/internal/interaction-harness/src/curves.ts
index e02f62694d..d3bad72ae8 100644
--- a/internal/interaction-harness/src/curves.ts
+++ b/internal/interaction-harness/src/curves.ts
@@ -86,6 +86,13 @@ function animationRecorder(): void {
}[] = [];
// Each recorded animation's entry.
const entries = new WeakMap<Animation, (typeof log)[number]>();
+ // CSS runs whose end event came while a rendering trace ran, with the
+ // event's time (real) and the active time the event reports.
+ const endedInTrace: {
+ entry: (typeof log)[number];
+ at: number;
+ elapsedMs: number;
+ }[] = [];
// The times kept below are real: a page time plus the span a page freeze
// stood still so far. A later freeze then leaves them where they were.
const span = () =>
@@ -353,12 +360,42 @@ function animationRecorder(): void {
// event came before it finished, and a cancelled run never finishes: under
// load, a CSS exit reversed partway sent `transitionend` at current time 0,
// still `running`, and was cancelled a frame later with no finish event.
+ // Chromium sends a run's end event before its finish event, so the run is
+ // still unfinished here. While a rendering trace runs, no run's state is
+ // read, as in the cancel wrapper below. That read flushes style, and lays
+ // out the run's anchored layer at the end of its own window. Only the newest
+ // run the event names is kept: an older run of that name that the page cut
+ // short stays unfinished. The recorder's resume() dates the kept run from
+ // what it stored.
const onEnd = (event: Event) => {
+ if (tracing()) {
+ for (let i = log.length - 1; i >= 0; i--) {
+ const entry = log[i];
+ if (!isRunOf(entry, event)) {
+ continue;
+ }
+ if (entry.finishedAt == null) {
+ endedInTrace.push({
+ entry,
+ at: performance.now() + span(),
+ // The event carries the active time, so nothing is read from the
+ // run.
+ elapsedMs:
+ 1000 *
+ Number(
+ (event as AnimationEvent | TransitionEvent).elapsedTime || 0,
+ ),
+ });
+ }
+ return;
+ }
+ return;
+ }
for (const entry of log) {
if (
entry.finishedAt == null &&
- atEnd(entry.animation) &&
- isRunOf(entry, event)
+ isRunOf(entry, event) &&
+ atEnd(entry.animation)
) {
dateFinish(entry, null);
}
@@ -436,8 +473,30 @@ function animationRecorder(): void {
record();
}
},
- // Catches up on what started during a trace, then runs its frames again.
+ // Dates the CSS runs that ended during a trace, then catches up on what
+ // started during it and runs its frames again. A run ends where its start
+ // puts its end, through its specified timing, as the cancel wrapper reads
+ // it. Its stored start comes first: the page may have cancelled the run at
+ // its end since then. Without one, the end event's time and active time
+ // stand in.
resume: () => {
+ for (const {entry, at, elapsedMs} of endedInTrace.splice(0)) {
+ if (entry.finishedAt != null) {
+ continue;
+ }
+ const timing = entry.animation.effect?.getTiming();
+ const delay = Number(timing?.delay ?? 0);
+ const duration =
+ typeof timing?.duration === 'number' ? timing.duration : 0;
+ const end =
+ delay +
+ duration * Number(timing?.iterations ?? 1) +
+ Number(timing?.endDelay ?? 0);
+ const speed = Math.abs(entry.animation.playbackRate || 1);
+ entry.finishStart = entry.startedAt ?? at - (delay + elapsedMs) / speed;
+ entry.startedAt ??= entry.finishStart;
+ entry.finishedAt = entry.finishStart + end / speed;
+ }
record();
loop();
},
@@ -468,6 +527,7 @@ function animationRecorder(): void {
log.length = 0;
unread.length = 0;
unstarted = [];
+ endedInTrace.length = 0;
},
};
}
diff --git a/internal/interaction-harness/src/harness.interaction.browser.spec.ts b/internal/interaction-harness/src/harness.interaction.browser.spec.ts
index ff47991cc6..4d165fb60a 100644
--- a/internal/interaction-harness/src/harness.interaction.browser.spec.ts
+++ b/internal/interaction-harness/src/harness.interaction.browser.spec.ts
@@ -2637,6 +2637,206 @@ test.describe('frame evidence', () => {
expect(started.map(a => a.durationMs)).toEqual([600, 600]);
});
+ // The page's listener for the end-of-run proofs below, on the anchored
+ // fixture. It is a capture listener on the document added after the
+ // recorder's, so it runs after the recorder's. It sets a mark the trace
+ // records, and a window that ends at that mark compares times on the
+ // trace's own clock. `layOutAtEnd` first forces a layout of the target:
+ // the control.
+ async function markEndListeners(page: Page) {
+ await page.evaluate(() => {
+ const w = window as unknown as {
+ __end: {stamp: number};
+ __layOutAtEnd: boolean;
+ };
+ w.__end = {stamp: 0};
+ w.__layOutAtEnd = false;
+ document.addEventListener(
+ 'animationend',
+ event => {
+ const el = event.target as HTMLElement;
+ if (w.__layOutAtEnd) {
+ el.style.minWidth = '1px';
+ void el.offsetWidth;
+ el.style.minWidth = '';
+ }
+ performance.mark('harness-test-end-listeners-ran');
+ w.__end = {stamp: performance.timeOrigin + event.timeStamp};
+ },
+ true,
+ );
+ });
+ }
+
+ // The time of the last mark named `name` in a trace that kept its events.
+ function markIn(
+ trace: Awaited<ReturnType<typeof traceRendering>>,
+ name: string,
+ ): number {
+ const marks = (trace.mainThread ?? []).filter(e => e.name === name);
+ const mark = marks.at(-1);
+ if (mark == null) {
+ throw new Error(`the trace kept no ${name} mark`);
+ }
+ return mark.t;
+ }
+
+ test("a CSS animation's end inside a trace costs no Layout from the recorder, with an earlier run of its name cut short, and only the runs that ended are reported, each dated where its start puts its end", async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'rendering traces are Chromium-only (README: engine limits)',
+ );
+ await page.route('http://anchored.test/', route =>
+ route.fulfill({contentType: 'text/html', body: ANCHORED}),
+ );
+ await page.goto('http://anchored.test/');
+ const pop = page.locator('#pop');
+ // The recorder runs, and its listeners are on the document by now.
+ await waitForRest(pop);
+ await page.addStyleTag({
+ content:
+ '@keyframes fade { from { opacity: 0.5 } to { opacity: 1 } } #pop.fade { animation: fade 300ms linear; }',
+ });
+ await markEndListeners(page);
+ const endOnce = async (layOutAtEnd: boolean) => {
+ await page.evaluate(layOut => {
+ const w = window as unknown as {
+ __end: {stamp: number};
+ __layOutAtEnd: boolean;
+ };
+ w.__end = {stamp: 0};
+ w.__layOutAtEnd = layOut;
+ }, layOutAtEnd);
+ const trace = await traceRendering(
+ page,
+ async () => {
+ await pop.evaluate(el => {
+ el.classList.add('fade');
+ });
+ await page.waitForFunction(
+ () =>
+ (window as unknown as {__end: {stamp: number}}).__end.stamp > 0,
+ undefined,
+ {polling: 50},
+ );
+ },
+ {keepEvents: true},
+ );
+ const {stamp} = await page.evaluate(
+ () => (window as unknown as {__end: {stamp: number}}).__end,
+ );
+ await pop.evaluate(el => {
+ el.classList.remove('fade');
+ });
+ // From a millisecond before the end event's coarse time stamp to the
+ // mark after the recorder's end listener.
+ return (
+ countBetween(
+ trace,
+ stamp - 1,
+ markIn(trace, 'harness-test-end-listeners-ran'),
+ ).Layout ?? 0
+ );
+ };
+ // An earlier run of the same name, cut short outside any trace, never
+ // finishes. It stays unfinished in the recorder's log, so each end below
+ // has another run of its name to read.
+ const watch = await watchAnimations(pop);
+ await pop.evaluate(el => {
+ el.classList.add('fade');
+ });
+ await waitForAnimation(pop);
+ await pop.evaluate(el => {
+ el.classList.remove('fade');
+ });
+ for (let run = 0; run < 3; run++) {
+ expect(await endOnce(false)).toBe(0);
+ }
+ // Only the three runs that ended are reported, each where its start puts
+ // its end. The run cut short is not reported as finished.
+ const ended = await watch.started();
+ expect(ended).toHaveLength(3);
+ for (const run of ended) {
+ expect(run.finishedAt).not.toBeNull();
+ expect(Math.abs((run.finishedAt ?? 0) - run.to)).toBeLessThan(1);
+ }
+ // Control: a layout forced in that span is counted.
+ expect(await endOnce(true)).toBeGreaterThan(0);
+ });
+
+ test('an end event that comes before its run finishes, inside a trace, costs no Layout, and the recorder dates the run from the start it stored once the trace ends', async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'rendering traces are Chromium-only (README: engine limits)',
+ );
+ await page.route('http://anchored.test/', route =>
+ route.fulfill({contentType: 'text/html', body: ANCHORED}),
+ );
+ await page.goto('http://anchored.test/');
+ const pop = page.locator('#pop');
+ await waitForRest(pop);
+ await page.addStyleTag({
+ content:
+ '@keyframes fade { from { opacity: 0.5 } to { opacity: 1 } } #pop.fade { animation: fade 300ms linear; }',
+ });
+ await markEndListeners(page);
+ // Chromium can send a CSS run's end event a frame before the run
+ // finishes. A page that cancels the run at that end gets no finish event.
+ // The proof sends that end event itself, while the run plays, and then
+ // cancels the run. A style write first leaves style to restyle, as at a
+ // run's real end.
+ const early = async (layOutAtEnd: boolean) => {
+ const watch = await watchAnimations(pop);
+ await pop.evaluate(el => {
+ el.classList.add('fade');
+ });
+ await waitForAnimation(pop);
+ await page.evaluate(layOut => {
+ (window as unknown as {__layOutAtEnd: boolean}).__layOutAtEnd = layOut;
+ }, layOutAtEnd);
+ const trace = await traceRendering(
+ page,
+ () =>
+ pop.evaluate(el => {
+ performance.mark('harness-test-early-end');
+ el.style.minWidth = '1px';
+ el.dispatchEvent(
+ new AnimationEvent('animationend', {
+ animationName: 'fade',
+ elapsedTime: 0.1,
+ }),
+ );
+ el.style.minWidth = '';
+ el.classList.remove('fade');
+ }),
+ {keepEvents: true},
+ );
+ const layouts =
+ countBetween(
+ trace,
+ markIn(trace, 'harness-test-early-end'),
+ markIn(trace, 'harness-test-end-listeners-ran'),
+ ).Layout ?? 0;
+ return {layouts, watch};
+ };
+ const first = await early(false);
+ expect(first.layouts).toBe(0);
+ // The recorder kept that end, and dated the run once the trace ended,
+ // from the start it stored and the run's timing.
+ const runs = await first.watch.started();
+ expect(runs).toHaveLength(1);
+ expect(runs[0].finishedAt).not.toBeNull();
+ expect(Math.abs((runs[0].finishedAt ?? 0) - runs[0].to)).toBeLessThan(1);
+ // Control: a layout forced in that span is counted.
+ expect((await early(true)).layouts).toBeGreaterThan(0);
+ });
+
test('a waitForRest awaited inside a traced body stands down too, so the trace counts no Layout from it', async ({
page,
browserName,