diff --git a/.changeset/3425-ghost-fade-end.md b/.changeset/3425-ghost-fade-end.md
new file mode 100644
index 0000000000..8941e8e846
--- /dev/null
+++ b/.changeset/3425-ghost-fade-end.md
@@ -0,0 +1,5 @@
+---
+"@schlessera/brain-ui-kit": patch
+---
+
+End the loading ghost's handoff when its fade ends, not 600ms after the data arrives, so a late first frame no longer removes the ghost from partial opacity. Where no fade runs (reduced motion, `animation: none`) the handoff still ends after 600ms.
diff --git a/docs/decisions/design-kit/loading.md b/docs/decisions/design-kit/loading.md
index 40f3cf3693..5235a6e39c 100644
--- a/docs/decisions/design-kit/loading.md
+++ b/docs/decisions/design-kit/loading.md
@@ -143,6 +143,23 @@ so ellipsis does not cut off blurred ends. Reduced motion hides the entire
band and disables every translation; print hides ghosts and the band. The
existing instant reduced-motion handoff and stream tail rules remain.
+### D53 addendum — the handoff ends on its fades' end (#3425, 2026-11-15)
+
+The handoff now ends when the item's own fades end, not on a 600ms timer
+started at the arrival commit (`useArrival`,
+`packages/ui-kit/src/internal/GhostText.tsx:216-248`). The fades start on the
+first frame the browser renders after the commit. On a loaded browser that
+frame can come hundreds of ms late, and the commit timer then removed the
+ghost from partial opacity, part-way through its fade. Even unloaded, the timer
+ended the fade a frame early. Each consumer hands its root element to the hook,
+which waits on that frame's running `ghost-in` and `ghost-out` animations.
+
+Where no fade runs, the handoff still ends after `HANDOFF_MS`. That covers
+reduced motion's 0s fades, `animation: none` and a DOM without Web Animations.
+A fade that has not started `FIRST_FRAME_MS` (3s) after the commit means the
+document renders no frames, and the handoff ends then rather than hold the
+ghost forever. The 600ms fade, its easing and its keyframes are unchanged.
+
diff --git a/docs/process/test-waits.md b/docs/process/test-waits.md
index 430e8ca61b..2b71e5babf 100644
--- a/docs/process/test-waits.md
+++ b/docs/process/test-waits.md
@@ -587,7 +587,9 @@ The nine former 640 ms settlements in `packages/ui-kit/tests/ghost-text.test.tsx
retain their assertions. The test captures every global timeout registered by
these mounted components, including a wrongly configured delay. Its independent
600 ms oracle checks the actual `useArrival` effect (`useArrival`,
-`packages/ui-kit/src/internal/GhostText.tsx:181-194`). At 599 ms the same outgoing
+`packages/ui-kit/src/internal/GhostText.tsx:216-248`). happy-dom computes no CSS
+animations, so no fade runs and the hook ends the handoff on its 600 ms
+fallback timer. Stand-in fades cover the path where a fade runs (#3425). At 599 ms the same outgoing
and incoming nodes must remain; at 600 ms the real callback runs inside React
`act`, whose committed result must remove both handoff classes. Neither an
arbitrary microtask nor immediate absence proves completion.
@@ -614,13 +616,15 @@ in the successor. The original glyph, role, style, accessibility, inertness,
interaction, ordering and loaded-state assertions stay in this file.
Native proof remains unchanged and required: `playHandoff` in
-`packages/ui-kit/stories/_ghost.tsx` observes 300 ms mid-handoff opacity,
-320/720 px geometry, a 600 ms fade in animation time and removal within three
-rendered frames of that fade's end (#3417). LoadingToReady
+`packages/ui-kit/stories/_ghost.tsx` observes mid-handoff opacity,
+320/720 px geometry, a 600 ms fade in animation time, a fade that ends before
+removal (#3425) and removal within three rendered frames of that fade's end
+(#3417). LoadingToReady
stories run in both Storybook theme projects. Chromium's
`packages/ui-kit/tests/visual/ghost-handoff.visual.tsx` retains both themes,
-input-orchestration and main-thread-stall exclusion, and the mutation holding
-one width's ghost 200 ms past its fade that still fails.
+input-orchestration and main-thread-stall exclusion, a long task right after
+the commit that delays the fades' start (#3425), and the mutation holding one
+width's ghost 400 ms past its fade that still fails.
Logical component time proves none of CSS rasterization, native elapsed
animation budgets or geometry. Production JavaScript and CSS remain 600 ms.
diff --git a/packages/ui-kit/src/conversation/StreamingAnswer.tsx b/packages/ui-kit/src/conversation/StreamingAnswer.tsx
index 4446f2fdff..d63bb06e46 100644
--- a/packages/ui-kit/src/conversation/StreamingAnswer.tsx
+++ b/packages/ui-kit/src/conversation/StreamingAnswer.tsx
@@ -1,5 +1,5 @@
import { GhostBand } from "../internal/GhostBand.js";
-import type { CSSProperties, KeyboardEvent } from "react";
+import { useRef, type CSSProperties, type KeyboardEvent } from "react";
import { GhostText, INCOMING, useArrival } from "../internal/GhostText.js";
import { StatusDot } from "../primitives/StatusDot.js";
@@ -78,7 +78,8 @@ export function StreamingAnswer(p: StreamingAnswerProps) {
const canStop = p.stoppable !== false;
const act = Boolean(p.onStop);
const waiting = p.bars !== false && !text;
- const arriving = useArrival(waiting);
+ const frame = useRef(null);
+ const arriving = useArrival(waiting, frame);
// Code points, not UTF-16 units, so the tail never splits a character.
const chars = Array.from(text);
const split = Math.max(0, chars.length - TAIL);
@@ -100,6 +101,7 @@ export function StreamingAnswer(p: StreamingAnswerProps) {
return (
(null);
+ const arriving = useArrival(loading, frame);
// The ghost's seed is this instance — kept per item key, not per list
// position — so re-ranking a row never regenerates its glyphs.
const id = useId();
@@ -311,6 +312,7 @@ export function ActionCard(p: ActionCardProps) {
return (
(null);
+ const arriving = useArrival(loading, frame);
// The ghost's seed is this instance — kept per item key, not per list
// position — so re-ranking a row never regenerates its glyphs.
const id = useId();
@@ -167,6 +168,7 @@ export function SearchResultCard(p: SearchResultCardProps) {
return (
{
+ const name = (a as CSSAnimation).animationName;
+ const duration = Number(a.effect?.getComputedTiming().duration ?? 0);
+ return name !== undefined && HANDOFF_FADES.has(name) && duration > 0;
+ });
+}
+
+/**
+ * True from the commit where `loading` turns false until that item's handoff
+ * fades have ended, so the item can draw its ghost under the arriving text.
+ * Per item: each list row calls it with its own flag and its own frame, so
+ * each one hands off when ITS data lands.
*
* Derived during render rather than in an effect, so the first ready frame
* already carries the outgoing ghost — an effect would paint one frame of bare
* text first, and the ghost would blink back over it.
+ *
+ * The handoff ends on the fades' own end (#3425), not on a timer from the
+ * commit: the fades start on the first frame the browser renders after the
+ * commit, and on a loaded browser that frame can be hundreds of ms late. A
+ * timer would then remove the ghost part-way through its fade. `frame` is the
+ * item's root element, holding its `.bk-ghost-out` and `.bk-ghost-in` layers.
+ *
+ * Where no fade runs — reduced motion, `animation: none`, a document without
+ * Web Animations — the handoff ends after `HANDOFF_MS`, the fade's length. A
+ * fade that has not started `FIRST_FRAME_MS` after the commit means the
+ * document renders no frames, and the handoff ends then.
*/
-export function useArrival(loading: boolean): boolean {
+export function useArrival(loading: boolean, frame: RefObject): boolean {
const [prev, setPrev] = useState(loading);
const [arriving, setArriving] = useState(false);
if (prev !== loading) {
@@ -187,9 +222,28 @@ export function useArrival(loading: boolean): boolean {
}
useEffect(() => {
if (!arriving) return;
- const timer = setTimeout(() => setArriving(false), HANDOFF_MS);
- return () => clearTimeout(timer);
- }, [arriving]);
+ let live = true;
+ const end = () => {
+ if (live) setArriving(false);
+ };
+ const fades = handoffFades(frame.current);
+ if (!fades.length) {
+ const timer = setTimeout(end, HANDOFF_MS);
+ return () => {
+ live = false;
+ clearTimeout(timer);
+ };
+ }
+ // A fade that is cancelled (its layer removed or restyled) has ended too.
+ void Promise.allSettled(fades.map((fade) => fade.finished)).then(end);
+ const frameless = setTimeout(() => {
+ if (fades.every((fade) => fade.startTime === null)) end();
+ }, FIRST_FRAME_MS);
+ return () => {
+ live = false;
+ clearTimeout(frameless);
+ };
+ }, [arriving, frame]);
return arriving;
}
diff --git a/packages/ui-kit/src/rows/FileRow.tsx b/packages/ui-kit/src/rows/FileRow.tsx
index fe2f97ea4f..1b01c3d08a 100644
--- a/packages/ui-kit/src/rows/FileRow.tsx
+++ b/packages/ui-kit/src/rows/FileRow.tsx
@@ -1,5 +1,5 @@
import { GhostBand } from "../internal/GhostBand.js";
-import { useId, type CSSProperties, type KeyboardEvent } from "react";
+import { useId, useRef, type CSSProperties, type KeyboardEvent } from "react";
import { Chip } from "../primitives/Chip.js";
import { GhostIconSlot, Ghosted, ghostLength, useArrival, useLastLengths, useLoadingValue } from "../internal/GhostText.js";
@@ -107,7 +107,8 @@ export function FileRow(p: FileRowProps) {
const act = Boolean(p.onClick) && p.view !== "loading";
const view = p.view || "ready";
const loading = view === "loading";
- const arriving = useArrival(loading);
+ const frame = useRef(null);
+ const arriving = useArrival(loading, frame);
// The ghost's seed is this instance — kept per item key, not per list
// position — so re-ranking a row never regenerates its glyphs.
const id = useId();
@@ -202,6 +203,7 @@ export function FileRow(p: FileRowProps) {
return (
(null);
+ const arriving = useArrival(loading, frame);
// The ghost's seed is this instance — kept per item key, not per list
// position — so re-ranking a row never regenerates its glyphs.
const id = useId();
@@ -189,6 +190,7 @@ export function QueueItemRow(p: QueueItemRowProps) {
return (
: null}
{arrived ? (
// One tree from arrival on: ending the handoff drops the overlay and a
diff --git a/packages/ui-kit/stories/_ghost.tsx b/packages/ui-kit/stories/_ghost.tsx
index 2592b4c00f..74505a7710 100644
--- a/packages/ui-kit/stories/_ghost.tsx
+++ b/packages/ui-kit/stories/_ghost.tsx
@@ -40,8 +40,9 @@ const opacity = (el: Element | null) => (el ? Number(getComputedStyle(el).opacit
* - the ghost's lines are the ready lines: the frame is the same height
* loading and ready, at 320px and at 720px, so nothing below it moves;
* - on arrival the outgoing ghost is laid over the content, not beside it;
- * - each outgoing ghost fades over the approved 600ms and is gone within
- * three rendered frames of its fade's end (#3417).
+ * - each outgoing ghost fades over the approved 600ms, stays until that
+ * fade has ended (#3425) and is gone within three rendered frames of its
+ * end (#3417).
*/
export async function playHandoff({
canvasElement,
@@ -85,10 +86,9 @@ export async function playHandoff({
// click resolves up to ~375ms after the frame commits its arriving layers
// (sometimes after the whole fade), so a fixed 300ms wait from there landed
// 370-770ms into the 600ms fade, after the ghost was gone. The harness
- // controls' height only shifted that by luck. A later point in the fade is
- // no safer: the ghost is removed on a timer started at the commit, and a
- // saturated browser can start the CSS animation 300ms late, so the window
- // both clocks agree on opens with the fade itself.
+ // controls' height only shifted that by luck. A saturated browser can
+ // start the CSS animation 300ms late, so the window opens with the fade
+ // itself, not with the commit.
const sampledFrame = handoffs[0]!;
// React commits the arrival inside the click, so it is observable now;
// without an outgoing layer there is no handoff to wait for.
@@ -199,6 +199,7 @@ export async function playHandoff({
await expect(clock.fadeMs, `${width}px: the outgoing ghost's fade, in animation time`).toBeLessThanOrEqual(FADE_MS);
await expect(clock.framesAfterFade, `${width}px: frames rendered with the ghost after its fade ended`).toBeLessThanOrEqual(FRAMES_AFTER_FADE);
await expect(clock.removed, `${width}px: the outgoing ghost was removed`).toBe(true);
+ await expect(clock.fadeEnded, `${width}px: the outgoing ghost's fade ended before its removal`).toBe(true);
}
await expect(canvasElement.querySelectorAll(".bk-ghost, .bk-ghost-out")).toHaveLength(0);
} finally {
diff --git a/packages/ui-kit/stories/_handoff-clock.ts b/packages/ui-kit/stories/_handoff-clock.ts
index b94537bf4a..5b0baddc89 100644
--- a/packages/ui-kit/stories/_handoff-clock.ts
+++ b/packages/ui-kit/stories/_handoff-clock.ts
@@ -11,8 +11,8 @@
* that genuinely holds the ghost past its fade keeps painting frames with it.
*
* The promise this checks is D53's: the outgoing ghost fades out over the
- * approved 600ms on its own animation clock and is gone within a few rendered
- * frames of that fade's end. The fade's length is read from its CSS animation timing at
+ * approved 600ms on its own animation clock, stays until that fade has ended,
+ * and is gone within a few rendered frames of its end (#3425). The fade's length is read from its CSS animation timing at
* arrival; its end is the browser's own `animationend`.
*/
@@ -21,11 +21,10 @@ export const FADE_MS = 600;
/**
* At most this many frames may render after the frame in which the fade ends.
- * The removal timer starts at the commit and the fade on a frame near it, so
- * the two end within a vsync of each other. Normally the ghost is removed
- * before its fade ends at all. The worst case observed with one CPU shared
- * with six busy loops was two frames, while a ghost held 200ms past its fade
- * renders about twelve at 60Hz.
+ * The component ends the handoff on the fade's own end (#3425), so removal
+ * normally lands in the next frame or two. The worst case observed with one
+ * CPU shared with six busy loops was two frames, while a ghost held 200ms past
+ * its fade renders about twelve at 60Hz.
*/
export const FRAMES_AFTER_FADE = 3;
@@ -48,6 +47,12 @@ export interface HandoffClock {
fadeMs?: number;
/** Frames rendered after the fade ended, up to removal. Zero if removal came first. */
framesAfterFade: number;
+ /**
+ * A `ghost-out` fade ended (`animationend`) before the ghost was removed. A
+ * ghost removed part-way through its fade, from partial opacity, leaves it
+ * false (#3425).
+ */
+ fadeEnded: boolean;
/** Frames rendered after arrival, up to removal. */
framesAfterArrival: number;
/**
@@ -79,6 +84,7 @@ export function watchHandoff(frame: HTMLElement, isArrival: (frame: HTMLElement)
arrived: false,
removed: false,
framesAfterFade: 0,
+ fadeEnded: false,
framesAfterArrival: 0,
settled: new Promise(resolve => { settle = resolve; }),
observe,
@@ -133,6 +139,7 @@ export function watchHandoff(frame: HTMLElement, isArrival: (frame: HTMLElement)
// Animation events dispatch before this frame's rAF callbacks, so the frame
// in which the fade ended is the first one counted after it.
fadeEndedAt ??= frames;
+ clock.fadeEnded = true;
}
const observer = new MutationObserver(observe);
diff --git a/packages/ui-kit/stories/_streaming-handoff.tsx b/packages/ui-kit/stories/_streaming-handoff.tsx
index 5cd5be1d81..604f0f61e0 100644
--- a/packages/ui-kit/stories/_streaming-handoff.tsx
+++ b/packages/ui-kit/stories/_streaming-handoff.tsx
@@ -52,6 +52,7 @@ export async function playStreamingHandoff({canvas, canvasElement, userEvent}: {
await expect(handoff.fadeMs, "the outgoing ghost's fade, in animation time").toBeLessThanOrEqual(FADE_MS);
await expect(handoff.framesAfterFade, "frames rendered with the ghost after its fade ended").toBeLessThanOrEqual(FRAMES_AFTER_FADE);
await expect(handoff.removed, "the outgoing ghost was removed").toBe(true);
+ await expect(handoff.fadeEnded, "the outgoing ghost's fade ended before its removal").toBe(true);
await expect(canvasElement.querySelectorAll(".bk-ghost, .bk-ghost-out")).toHaveLength(0);
for (let i = 1; i < TOKENS.length; i++) await userEvent.click(token);
diff --git a/packages/ui-kit/stories/states/Placeholder.stories.tsx b/packages/ui-kit/stories/states/Placeholder.stories.tsx
index 14a542d582..ab9a19b412 100644
--- a/packages/ui-kit/stories/states/Placeholder.stories.tsx
+++ b/packages/ui-kit/stories/states/Placeholder.stories.tsx
@@ -213,6 +213,7 @@ export const Arrived = meta.story({
await userEvent.click(await canvas.findByRole("button", { name: "Arrive" }));
await expect(box()).toBeNull();
const out = canvasElement.querySelector(".bk-ghost-out")!;
+ await expect(out, "the outgoing ghost is laid over the arriving content").not.toBeNull();
await expect(getComputedStyle(out).position).toBe("absolute");
await expect(getComputedStyle(out).animationName).toBe("ghost-out");
await expect(getComputedStyle(canvasElement.querySelector(".bk-ghost-in")!).animationName).toBe("ghost-in");
diff --git a/packages/ui-kit/tests/ghost-text.test.tsx b/packages/ui-kit/tests/ghost-text.test.tsx
index 5767aa9a88..d0400ac4c2 100644
--- a/packages/ui-kit/tests/ghost-text.test.tsx
+++ b/packages/ui-kit/tests/ghost-text.test.tsx
@@ -8,14 +8,14 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { Window } from "happy-dom";
-import { StrictMode, act, useEffect, useState, type ReactElement } from "react";
+import { StrictMode, act, useEffect, useRef, useState, type ReactElement } from "react";
import { createRoot } from "react-dom/client";
import { renderToStaticMarkup } from "react-dom/server";
import { StreamingAnswer } from "../src/conversation/StreamingAnswer.js";
import { ActionCard } from "../src/decisions/ActionCard.js";
import { SearchResultCard } from "../src/evidence/SearchResultCard.js";
-import { GhostText, HANDOFF_MS, ghostBlur, ghostString, useArrival } from "../src/internal/GhostText.js";
+import { FIRST_FRAME_MS, GhostText, HANDOFF_MS, ghostBlur, ghostString, useArrival } from "../src/internal/GhostText.js";
import { FileRow } from "../src/rows/FileRow.js";
import { QueueItemRow } from "../src/rows/QueueItemRow.js";
import { Placeholder } from "../src/states/Placeholder.js";
@@ -476,11 +476,12 @@ describe("arrival clock lifecycle", () => {
test("StrictMode effect replay cancels its first callback and unmount cancels the second", async () => {
function ArrivingOnMount() {
const [loading, setLoading] = useState(true);
- const arriving = useArrival(loading);
+ const frame = useRef(null);
+ const arriving = useArrival(loading, frame);
// A render-phase loading transition makes the actual arrival effect live
// on its first commit, so StrictMode replays that effect's cleanup/setup.
if (loading) setLoading(false);
- return
Odysseus arrives
;
+ return
Odysseus arrives
;
}
const m = await mount(() => );
expect(m.clock.registered.map(timer => timer.delay), "STRICT_EFFECT_SETUP_TWICE").toEqual([600, 600]);
@@ -496,6 +497,66 @@ describe("arrival clock lifecycle", () => {
expect(m.host.childNodes).toHaveLength(0);
});
+ // #3425: where a fade runs, the handoff ends on the fade's own end. happy-dom
+ // computes no CSS animations, so these give the frame stand-in fades; the
+ // native timing proof is Chromium's (`tests/visual/ghost-handoff.visual.tsx`).
+ function fade(duration = HANDOFF_MS) {
+ let finish!: () => void;
+ const finished = new Promise((resolve) => { finish = resolve; });
+ const animation = {
+ animationName: "ghost-out", playState: "running", startTime: null as number | null, finished,
+ effect: { getComputedTiming: () => ({ duration }) },
+ };
+ return { animation, finish };
+ }
+ async function mountFrame(animations: unknown[]) {
+ function Frame({ loading }: { loading: boolean }) {
+ const frame = useRef(null);
+ const arriving = useArrival(loading, frame);
+ return ;
+ }
+ const m = await mount((loading) => );
+ const node = m.host.querySelector("[data-frame]")!;
+ Object.defineProperty(node, "getAnimations", { configurable: true, value: () => animations });
+ return { ...m, arriving: () => node.dataset.arriving };
+ }
+
+ test("a running fade ends the handoff on its own end, not 600ms after the commit", async () => {
+ const out = fade();
+ const m = await mountFrame([out.animation]);
+ await m.land();
+ expect(m.clock.registered.map((timer) => timer.delay), "NO_600MS_TIMER_WITH_A_FADE").toEqual([FIRST_FRAME_MS]);
+ await m.clock.advance(HANDOFF_MS);
+ expect(m.arriving(), "FADE_STARTED_LATE_STILL_RUNS").toBe("true");
+ out.animation.startTime = 400; // Its first frame came, late.
+ await m.clock.advance(FIRST_FRAME_MS - HANDOFF_MS);
+ expect(m.arriving(), "A_STARTED_FADE_IS_NOT_FRAMELESS").toBe("true");
+ await act(async () => out.finish());
+ expect(m.arriving(), "ENDS_ON_THE_FADE").toBe("false");
+ await m.unmount();
+ });
+
+ test("a fade that never starts — no rendered frames — ends the handoff after FIRST_FRAME_MS", async () => {
+ const m = await mountFrame([fade().animation]);
+ await m.land();
+ await m.clock.advance(FIRST_FRAME_MS - 1);
+ expect(m.arriving()).toBe("true");
+ await m.clock.advance(1);
+ expect(m.arriving(), "FRAMELESS_DOCUMENT_ENDS").toBe("false");
+ await m.unmount();
+ });
+
+ test("a zero-length fade (reduced motion) ends the handoff after HANDOFF_MS", async () => {
+ const m = await mountFrame([fade(0).animation]);
+ await m.land();
+ expect(m.clock.registered.map((timer) => timer.delay)).toEqual([HANDOFF_MS]);
+ await m.clock.advance(HANDOFF_MS - 1);
+ expect(m.arriving()).toBe("true");
+ await m.clock.advance(1);
+ expect(m.arriving(), "NO_FADE_ENDS_ON_THE_TIMER").toBe("false");
+ await m.unmount();
+ });
+
test("failed assertion cleanup restores every descriptor and the successor starts clean", async () => {
const failed = environment;
let host!: HTMLElement;
diff --git a/packages/ui-kit/tests/visual/README.md b/packages/ui-kit/tests/visual/README.md
index 574c7905b2..1210d48f17 100644
--- a/packages/ui-kit/tests/visual/README.md
+++ b/packages/ui-kit/tests/visual/README.md
@@ -119,13 +119,15 @@ and play function as StreamingAnswer's `LoadingToReady` story;
Both count the handoff on the page's own clock (`watchHandoff`,
`stories/_handoff-clock.ts`, #3417): from the committed text/outgoing-ghost
layers to actual ghost removal, observed through native DOM mutations, the
-outgoing fade must last at most the approved 600ms of animation time and the
-ghost must be gone within three rendered frames of that fade's `animationend`.
-No wall-clock cap remains: a stalled runner delays the removal timer, the fade's
-end and every frame alike. Both transition observations are required.
+outgoing fade must last at most the approved 600ms of animation time, must
+reach its `animationend` before the ghost is removed (#3425), and the ghost
+must be gone within three rendered frames of that end. No wall-clock cap
+remains: a stalled runner delays the fade's end and every frame alike. Both
+transition observations are required.
The controls delay first-token dispatch, delay final observation after removal,
-and block the main thread for 150ms across the fade's end; all pass. A ghost
-retained 200ms past its fade and a fade slowed to 900ms still fail. Both themes
+block the main thread for 150ms across the fade's end, and block it for 300ms
+right after the arrival commit, so the fades start late; all pass. A ghost
+retained 400ms past its fade and a fade slowed to 900ms still fail. Both themes
retain the story's layout, geometry, nonempty token/tail and rendered-opacity
assertions; the approved fade stays 600ms.
diff --git a/packages/ui-kit/tests/visual/ghost-handoff.visual.tsx b/packages/ui-kit/tests/visual/ghost-handoff.visual.tsx
index 73fd1221a8..affb68d643 100644
--- a/packages/ui-kit/tests/visual/ghost-handoff.visual.tsx
+++ b/packages/ui-kit/tests/visual/ghost-handoff.visual.tsx
@@ -1,5 +1,5 @@
-/** Runtime regression for the handoff clock, with the real populated card (#1179, #3417). */
-import { expect, test, vi } from "vitest";
+/** Runtime regression for the handoff clock, with the real populated card (#1179, #3417, #3425). */
+import { expect, test } from "vitest";
import { createRoot } from "react-dom/client";
import { flushSync } from "react-dom";
import { Handoff, playHandoff } from "../../stories/_ghost.js";
@@ -37,12 +37,20 @@ function stallAfter(delay: number, ms: number) {
}, delay);
}
-const drive = (host: HTMLElement, beforeLand = 0, stall?: { at: number; ms: number }) => playHandoff({
+/** A long task in the arrival's own task, after React has committed it and
+ * before the browser can render the frame that starts its fades (#3425). */
+function stallNow(ms: number) {
+ const start = performance.now();
+ while (performance.now() - start < ms) { /* a long task */ }
+}
+
+const drive = (host: HTMLElement, beforeLand = 0, stall?: { at: number; ms: number }, commitStall = 0) => playHandoff({
canvasElement: host,
canvas: {findByRole: async (_role, {name}) => [...host.querySelectorAll("button")].find(b => b.textContent === name)!},
userEvent: {click: async element => {
if (element.textContent === "Land" && beforeLand) await new Promise(resolve => setTimeout(resolve, beforeLand));
(element as HTMLElement).click();
+ if (element.textContent === "Land" && commitStall) stallNow(commitStall);
if (element.textContent === "Land" && stall) stallAfter(stall.at, stall.ms);
await new Promise(resolve => setTimeout(resolve, 0));
}},
@@ -66,21 +74,30 @@ for (const theme of ["dark", "light"]) {
});
});
- test(`${theme}: a handoff held 200ms past its fade at only 720px still fails`, async () => {
+ // #3425: the fades start on the first frame after the commit. A long task
+ // right after the commit makes that frame late; the ghost must still fade
+ // to its end before it goes, rather than be cut at 600ms from the commit.
+ test(`${theme}: a long task right after arrival delays the fades, and each ghost still fades to its end`, async () => {
+ await withCard(theme, async host => {
+ await drive(host, 0, undefined, 300);
+ expect(host.querySelectorAll(".bk-ghost, .bk-ghost-out")).toHaveLength(0);
+ });
+ });
+
+ test(`${theme}: a handoff held 400ms past its fade at only 720px still fails`, async () => {
await withCard(theme, async host => {
- const nativeTimeout = globalThis.setTimeout;
- let handoffTimers = 0;
- const timer = vi.spyOn(globalThis, "setTimeout").mockImplementation(((...args: unknown[]) => {
- // Native timers and React execute normally. Hold only the second
- // frame's outgoing layer beyond budget; the first frame stays valid.
- if (args[1] === 600 && ++handoffTimers === 2) args[1] = 800;
- return Reflect.apply(nativeTimeout, globalThis, args);
- }) as typeof nativeTimeout);
+ // The handoff ends when both of its fades have. Hold only the second
+ // frame's incoming fade 400ms longer; its outgoing fade, and the first
+ // frame, stay valid, so the 720px ghost outlives its own fade. 400ms, not
+ // 200: a CPU-starved browser renders a 200ms hold in as few as three
+ // frames, inside the allowance.
+ const hold = document.createElement("style");
+ hold.textContent = '[data-width="720"] .bk-ghost-in { animation-duration: 1000ms !important; }';
+ document.head.append(hold);
try {
await expect(drive(host)).rejects.toThrow(/720px: frames rendered with the ghost after its fade ended/);
- expect(handoffTimers).toBe(2);
} finally {
- timer.mockRestore();
+ hold.remove();
}
});
});
diff --git a/packages/ui-kit/tests/visual/ghost-media.visual.tsx b/packages/ui-kit/tests/visual/ghost-media.visual.tsx
index 660c3a81b9..ad4d5e9d48 100644
--- a/packages/ui-kit/tests/visual/ghost-media.visual.tsx
+++ b/packages/ui-kit/tests/visual/ghost-media.visual.tsx
@@ -5,7 +5,8 @@
* that brings the spectrum back under reduced motion fails here.
*/
import { commands } from "vitest/browser";
-import { afterEach, expect, test } from "vitest";
+import { afterEach, expect, test, vi } from "vitest";
+import { FIRST_FRAME_MS, HANDOFF_MS } from "../../src/internal/GhostText.js";
import * as placeholder from "../../stories/states/Placeholder.stories.js";
interface Story { run: (context?: { globals?: Record }) => Promise }
@@ -55,8 +56,11 @@ test("without reduced motion the frame sweep runs through three masked windows",
}
});
-test("reduced motion: the handoff is instant", async () => {
- await commands.ghostMedia("reduce", "screen");
+/**
+ * Reload and arrive Placeholder's `Arrived` story once more, recording every
+ * timer delay registered from the arrival on (#3425). Real timers still run.
+ */
+async function arrive(check: () => void, before?: () => void) {
// The story's own play has already arrived once; load again, then arrive.
await run(placeholder.Arrived);
const button = (label: string) => [...document.querySelectorAll("button")].find((b) => b.textContent === label)!;
@@ -64,10 +68,49 @@ test("reduced motion: the handoff is instant", async () => {
button("Reload").click();
await frames();
expect(document.querySelector("[aria-busy]")).not.toBeNull();
- button("Arrive").click();
- await frames();
- expect(Number(getComputedStyle(document.querySelector(".bk-ghost-out")!).opacity)).toBe(0);
- expect(Number(getComputedStyle(document.querySelector(".bk-ghost-in")!).opacity)).toBe(1);
+ before?.();
+ const delays: number[] = [];
+ const native = globalThis.setTimeout;
+ const timer = vi.spyOn(globalThis, "setTimeout").mockImplementation(((...args: unknown[]) => {
+ delays.push(Number(args[1] ?? 0));
+ return Reflect.apply(native, globalThis, args);
+ }) as typeof native);
+ try {
+ button("Arrive").click();
+ await frames();
+ expect(document.querySelector(".bk-ghost-out"), "the outgoing ghost stays until HANDOFF_MS").not.toBeNull();
+ check();
+ // Never waiting for an animation end that does not come: the ghost goes.
+ await vi.waitFor(() => expect(document.querySelectorAll(".bk-ghost, .bk-ghost-out")).toHaveLength(0), { timeout: FIRST_FRAME_MS - HANDOFF_MS, interval: 20 });
+ } finally {
+ timer.mockRestore();
+ }
+ // With no fade to wait for, the handoff ends on its 600ms timer, not on the
+ // fallback for a document that renders no frames.
+ expect(delays, "the handoff's 600ms timer").toContain(HANDOFF_MS);
+ expect(delays, "no wait for a first frame").not.toContain(FIRST_FRAME_MS);
+}
+
+test("reduced motion: the handoff is instant, and ends after HANDOFF_MS", async () => {
+ await commands.ghostMedia("reduce", "screen");
+ await arrive(() => {
+ expect(Number(getComputedStyle(document.querySelector(".bk-ghost-out")!).opacity)).toBe(0);
+ expect(Number(getComputedStyle(document.querySelector(".bk-ghost-in")!).opacity)).toBe(1);
+ });
+});
+
+test("animation: none: no fade runs, and the handoff still ends after HANDOFF_MS", async () => {
+ const none = document.createElement("style");
+ none.textContent = ".bk-ghost-in, .bk-ghost-out { animation: none !important; }";
+ try {
+ // After the story's own play, which checks the fades it normally has.
+ await arrive(() => {
+ expect(getComputedStyle(document.querySelector(".bk-ghost-out")!).animationName).toBe("none");
+ expect(document.querySelector(".bk-ghost-out")!.getAnimations()).toHaveLength(0);
+ }, () => document.head.append(none));
+ } finally {
+ none.remove();
+ }
});
test("print: every ghost is hidden and keeps its box", async () => {
diff --git a/packages/ui-kit/tests/visual/streaming-handoff.visual.tsx b/packages/ui-kit/tests/visual/streaming-handoff.visual.tsx
index d7a7775f75..01702ff156 100644
--- a/packages/ui-kit/tests/visual/streaming-handoff.visual.tsx
+++ b/packages/ui-kit/tests/visual/streaming-handoff.visual.tsx
@@ -1,4 +1,4 @@
-/** The separate first-token story's real-browser clock controls (#1185, #3417). */
+/** The separate first-token story's real-browser clock controls (#1185, #3417, #3425). */
import { expect, test, vi } from "vitest";
import { createRoot } from "react-dom/client";
import { flushSync } from "react-dom";
@@ -35,7 +35,14 @@ function stallAfter(delay: number, ms: number) {
}, delay);
}
-async function drive(host: HTMLElement, beforeInput = 0, afterInput = 0, stall?: { at: number; ms: number }) {
+/** A long task in the arrival's own task, after React has committed it and
+ * before the browser can render the frame that starts its fades (#3425). */
+function stallNow(ms: number) {
+ const start = performance.now();
+ while (performance.now() - start < ms) { /* a long task */ }
+}
+
+async function drive(host: HTMLElement, beforeInput = 0, afterInput = 0, stall?: { at: number; ms: number }, commitStall = 0) {
const trace: { started: number; input?: number; arrived?: number; removed?: number } = { started: performance.now() };
const observe = () => {
const now = performance.now();
@@ -57,6 +64,7 @@ async function drive(host: HTMLElement, beforeInput = 0, afterInput = 0, stall?:
if (first && beforeInput) await new Promise(resolve => setTimeout(resolve, beforeInput));
if (first) trace.input = performance.now();
(element as HTMLElement).click();
+ if (first && commitStall) stallNow(commitStall);
if (first && stall) stallAfter(stall.at, stall.ms);
await new Promise(resolve => setTimeout(resolve, first ? afterInput : 0));
} },
@@ -68,7 +76,7 @@ async function drive(host: HTMLElement, beforeInput = 0, afterInput = 0, stall?:
expect(host.querySelectorAll(".bk-ghost, .bk-ghost-out")).toHaveLength(0);
} finally {
console.log("STREAM_HANDOFF_CONTROL", JSON.stringify({
- beforeInput, afterInput, stall: stall ?? null,
+ beforeInput, afterInput, stall: stall ?? null, commitStall,
inputMs: trace.input === undefined ? null : trace.input - trace.started,
arrivalMs: trace.arrived === undefined ? null : trace.arrived - trace.started,
handoffMs: trace.arrived === undefined || trace.removed === undefined ? null : trace.removed - trace.arrived,
@@ -96,19 +104,26 @@ for (const theme of ["dark", "light"]) {
await withStream(theme, host => drive(host, 0, 0, { at: 590, ms: 150 }));
});
- if (theme === "light") test(`${theme}: a first-token ghost held 200ms past its fade still fails`, async () => {
+ // #3425: the fades start on the first frame after the commit. A long task
+ // right after the first token's commit makes that frame late; the ghost must
+ // still fade to its end, rather than be cut at 600ms from the commit.
+ test(`${theme}: a long task right after the first token delays the fade, and the ghost still fades to its end`, async () => {
+ await withStream(theme, host => drive(host, 0, 0, undefined, 300));
+ });
+
+ if (theme === "light") test(`${theme}: a first-token ghost held 400ms past its fade still fails`, async () => {
await withStream(theme, async host => {
- const nativeTimeout = globalThis.setTimeout;
- let handoffTimers = 0;
- const timer = vi.spyOn(globalThis, "setTimeout").mockImplementation(((...args: unknown[]) => {
- if (args[1] === 600) { handoffTimers++; args[1] = 800; }
- return Reflect.apply(nativeTimeout, globalThis, args);
- }) as typeof nativeTimeout);
+ // The handoff ends when both of its fades have. Hold the incoming fade
+ // 400ms longer, so the outgoing ghost outlives its own fade. 400ms, not
+ // 200: a CPU-starved browser renders a 200ms hold in as few as three
+ // frames, inside the allowance.
+ const hold = document.createElement("style");
+ hold.textContent = ".bk-ghost-in { animation-duration: 1000ms !important; }";
+ document.head.append(hold);
try {
await expect(drive(host)).rejects.toThrow(/frames rendered with the ghost after its fade ended/);
- expect(handoffTimers, "a real first-token handoff was held past its fade").toBe(1);
} finally {
- timer.mockRestore();
+ hold.remove();
}
});
});
@@ -121,12 +136,14 @@ for (const theme of ["dark", "light"]) {
document.head.append(slow);
let handoffTimers = 0;
const timer = vi.spyOn(globalThis, "setTimeout").mockImplementation(((...args: unknown[]) => {
- if (args[1] === 600) { handoffTimers++; args[1] = 900; }
+ if (args[1] === 600) handoffTimers++;
return Reflect.apply(nativeTimeout, globalThis, args);
}) as typeof nativeTimeout);
try {
+ // The component waits for the slowed fade itself (#3425); the clock
+ // still rejects a fade longer than D53's 600ms.
await expect(drive(host)).rejects.toThrow(/the outgoing ghost's fade, in animation time/);
- expect(handoffTimers, "the slowed handoff was the real first-token one").toBe(1);
+ expect(handoffTimers, "a running fade ends the handoff, not a 600ms timer").toBe(0);
} finally {
timer.mockRestore();
slow.remove();
diff --git a/tests/dom-global-restoration.test.ts b/tests/dom-global-restoration.test.ts
index fe9146662a..71bb664ee7 100644
--- a/tests/dom-global-restoration.test.ts
+++ b/tests/dom-global-restoration.test.ts
@@ -44,7 +44,7 @@ afterAll(() => {
new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited,
]);
expect(exitCode, stdout + stderr).toBe(0);
- expect(stderr).toMatch(/\b63 pass\b/);
+ expect(stderr).toMatch(/\b66 pass\b/);
const receipts = stdout.split("\n").filter(line => line.startsWith("DOM_DESCRIPTOR_RECEIPT "));
expect(receipts).toHaveLength(1);
expect(JSON.parse(receipts[0]!.slice("DOM_DESCRIPTOR_RECEIPT ".length))).toEqual(keys.map(key => ({ key, equal: true })));