Files
paseo/packages/app/e2e/support/helpers/markdown-root-stability.ts
T
Mohamed Boudra 6215e08efe Smooth streaming replies with a continuous left-to-right fade (#4859)
* feat(app): reveal streaming text as one continuous fade front

Streaming assistant text is released by word and every character fades in
over the same 150 ms envelope from a start time owned by the message. Start
times never decrease in reading order, so a line paints as a single front
moving left to right, however the text is chunked. Per-word envelopes with an
internal stagger let the next word's first letter overtake the previous word's
last letter, which read as holes and flashing words at the real frame rate;
100 ms frame strips hid it.

Native renderers receive the fade ranges as a prop on a host view wrapping the
root Text, so ranges and text land in the same Fabric mount transaction. The
earlier binding sent ranges through a separate async module call keyed by view
tag and had to reconcile them against the view's text; on a fast phone the UI
thread lags JS by several commits, mounts and calls interleave, and every
reconciliation heuristic guessed wrong. Native code no longer infers newness
or creates start times.

The mock load-test provider now separates cycles with a blank line so a cycle
heading is not appended to the previous paragraph.

* fix(ci): refresh streaming dependencies and isolate E2E setup

* test(app): distinguish fade cleanup from Markdown replacement

* test(app): detect restarted fades during Markdown updates

* docs(app): keep streaming guidance focused on constraints and QA

* test(app): control animation time in Android fade assertions

Fixed wall-clock sleeps let emulator scheduling select the sampled animation frame. Inject the animator time source and drive paint at exact timestamps within one UI-thread operation; production keeps the system clock. Verify the mid-fade sample and the exact cleanup boundary without sleeps, polling, or retries.

* fix(test): compile the desktop renderer before lifecycle checks

The lifecycle fixture treated Metro /status as app readiness. Its first
Settings click therefore spent its 90-second UI budget compiling the cold
bundle. An isolated cold-cache run restricted to one CPU reproduced the
click timeout before the app runtime had loaded.

Reuse the browser suite's existing bundle warmup before launching Electron,
and preserve Metro output in the lifecycle artifacts. The UI timeout,
build-request timeout, lifecycle assertions and product behavior are unchanged.

CI did not preserve Metro output, so its precise startup timing is not
recoverable from the failed run. The retained log makes subsequent startup
failures diagnosable without relying only on an empty renderer text dump.

Validation: three complete lifecycle E2E runs under private Xvfb displays;
existing Metro readiness tests; app typecheck; targeted lint; root format.

* test(file-observer): await burst delivery through native recovery

The deletion phase required every event within 10 seconds, but native
coalescing recovery uses a 30-second safety audit followed by the existing
reconciliation debounce. An idle diagnostic excludes that delayed audit
and therefore cannot act as a completion barrier.

Await the required delivered events instead, preserving every deletion
assertion and the existing overall test watchdog. A real-filesystem test
with controlled native notifications reproduces 95 outstanding paths at
the old deadline and verifies completion when the safety audit delivers
them. No production observer behavior changes.

* test(file-observer): verify burst recovery through public events

The controlled-clock regression constructed a private native backend,
bypassing the interface used by consumers. Consolidate recovery coverage
into the public observer integration test instead: drive real writes,
deletes and directory renames, then await every required public event,
including the 450 surviving files at their renamed paths.

No public capability was added: subscribe callbacks already express
completion. No production behavior or test timeout changes.

* test(app): drive Android fade tests through the native host

The instrumentation suite constructed TailFadeInAnimator directly, advanced
its private clock, and counted FadeInSpan instances. It now mounts the
WordFadeHost that React mounts, feeds it the ranges prop the bridge sends,
and asserts rendered pixels: hidden before a start time, a monotone front
inside and across words, settled frames equal to the baseline, and no frame
callbacks left after settling. Span counts and internal timing state are no
longer asserted.

Choreographer cannot be advanced deterministically from a test and the fade
epoch is the message's wall-clock start time, so the host takes a
WordFadeFrameClock (time plus frame callbacks) as its smallest public seam;
production keeps the Choreographer-backed default.

Fixture text is sized in pixels so every sample stays on one line at any
density; at 420 dpi the 32sp fixture wrapped and the column helper summed
glyphs from the first line.
2026-09-15 03:15:24 +02:00

197 lines
8.0 KiB
TypeScript

/**
* Observes a streaming Markdown block and classifies DOM churn.
*
* The word fade wraps each arriving word in a `data-word-fade` span carrying
* the word's start time, and collapses it back into plain text once the fade
* has settled, so text nodes around the tail and settled spans come and go by
* design. When Markdown re-parses and a word's rendered offset shifts, its span
* is re-created with the same start time and the fade resumes. Two things are
* defects:
*
* - `replacedElements`: an element other than a fade span left the block, so
* Markdown re-created a mounted descendant. Text nodes alone cannot form a
* Markdown descendant.
* - `restartedFades`: a fade span was removed before it settled and no span with
* that start time was added afterwards, so the word was faded again.
*
* Both functions run inside the page through `page.evaluate`, so they must be
* self-contained: no references to module scope.
*/
import type { Page } from "@playwright/test";
export interface MarkdownRootEvidence {
addedNodes: number;
characterDataMutations: number;
removedNodes: number;
replacedElements: number;
restartedFades: number;
}
interface MarkdownRootObserverWindow {
__markdownRootSettle?: () => MarkdownRootEvidence;
}
export function installMarkdownRootObserver(block: Element): void {
const fadeDurationMs = 150;
const frameMs = 16;
const evidence: MarkdownRootEvidence = {
addedNodes: 0,
characterDataMutations: 0,
removedNodes: 0,
replacedElements: 0,
restartedFades: 0,
};
// Unsettled removals waiting for a same-start-time addition. An addition
// only resumes a removal that already happened; React removes the old span
// before placing the new one within a commit.
const pendingResumes = new Map<string, number>();
const fadeSpans = (node: Node): HTMLElement[] => {
if (!(node instanceof HTMLElement)) return [];
return node.hasAttribute("data-word-fade")
? [node]
: Array.from(node.querySelectorAll<HTMLElement>("[data-word-fade]"));
};
// The renderer collapses a word when its last letter's animation ends. That
// letter starts at startedAt + spanMs * (letters - 1) / letters.
const isSettled = (span: HTMLElement) => {
const letters = Math.max(1, span.childElementCount);
const settledAt =
Number(span.dataset.fadeStarted) +
(Number(span.dataset.fadeSpan) * (letters - 1)) / letters +
fadeDurationMs;
return Number.isFinite(settledAt) && Date.now() + frameMs >= settledAt;
};
const handle = (records: MutationRecord[]) => {
for (const record of records) {
evidence.addedNodes += record.addedNodes.length;
evidence.removedNodes += record.removedNodes.length;
if (record.type === "characterData") evidence.characterDataMutations += 1;
for (const node of record.removedNodes) {
// Any removed element other than a fade span is a replaced descendant,
// whatever it contains. Fade spans it carried away were removed too.
if (node instanceof Element && !node.hasAttribute("data-word-fade")) {
evidence.replacedElements += 1;
}
for (const span of fadeSpans(node)) {
const started = span.dataset.fadeStarted;
if (!started || isSettled(span)) continue;
pendingResumes.set(started, (pendingResumes.get(started) ?? 0) + 1);
}
}
for (const node of record.addedNodes) {
for (const span of fadeSpans(node)) {
const started = span.dataset.fadeStarted;
const pending = started ? pendingResumes.get(started) : undefined;
if (!started || pending === undefined) continue;
if (pending > 1) pendingResumes.set(started, pending - 1);
else pendingResumes.delete(started);
}
}
}
};
const observer = new MutationObserver(handle);
observer.observe(block, { characterData: true, childList: true, subtree: true });
const settle = () => {
handle(observer.takeRecords());
observer.disconnect();
let restarted = 0;
for (const count of pendingResumes.values()) restarted += count;
evidence.restartedFades = restarted;
return evidence;
};
(window as unknown as MarkdownRootObserverWindow).__markdownRootSettle = settle;
}
export function settleMarkdownRootObserver(): MarkdownRootEvidence {
const settle = (window as unknown as MarkdownRootObserverWindow).__markdownRootSettle;
if (!settle) throw new Error("installMarkdownRootObserver has not run on this page");
return settle();
}
// Synthetic streaming block: the same DOM shapes the fade renderer produces,
// driven by hand so each classification can be exercised in isolation.
const SYNTHETIC_BLOCK_ID = "markdown-root-stability-block";
export async function mountObservedSyntheticBlock(page: Page): Promise<void> {
await page.setContent(`<div id="${SYNTHETIC_BLOCK_ID}"><p>settled </p></div>`);
const block = await page.locator(`#${SYNTHETIC_BLOCK_ID}`).elementHandle();
if (!block) throw new Error("Expected the synthetic Markdown block to mount");
await page.evaluate(installMarkdownRootObserver, block);
}
type SyntheticMutation =
| "resume-fading-word"
| "restart-fading-word"
| "collapse-settled-word"
| "replace-paragraph"
| "replace-paragraph-keeping-fading-word";
async function mutateSyntheticBlock(page: Page, mutation: SyntheticMutation): Promise<void> {
await page.evaluate(
([blockId, kind]) => {
const p = document.querySelector(`#${blockId} > p`) as HTMLElement;
const fadingWord = (startedAt: number) => {
const span = document.createElement("span");
span.setAttribute("data-word-fade", "0");
span.dataset.fadeStarted = String(startedAt);
span.dataset.fadeSpan = "60";
span.textContent = "word";
return span;
};
const replaceParagraphWith = (child?: HTMLElement) => {
const next = document.createElement("p");
next.textContent = p.textContent;
if (child) next.append(child);
p.replaceWith(next);
};
// Wall-clock start times are unsettled at removal unless backdated.
const now = Date.now();
switch (kind) {
case "resume-fading-word":
p.append(fadingWord(now));
p.lastElementChild!.remove();
p.append(fadingWord(now));
return;
case "restart-fading-word":
p.append(fadingWord(now));
p.lastElementChild!.remove();
p.append(fadingWord(now + 1));
return;
case "collapse-settled-word":
p.append(fadingWord(now - 10_000));
p.lastElementChild!.remove();
p.append("word");
return;
case "replace-paragraph":
replaceParagraphWith();
return;
case "replace-paragraph-keeping-fading-word":
p.append(fadingWord(now));
replaceParagraphWith(fadingWord(now));
return;
}
},
[SYNTHETIC_BLOCK_ID, mutation] as const,
);
}
/** Remove a fading word and re-create it with the same start time. */
export const resumeFadingWord = (page: Page) => mutateSyntheticBlock(page, "resume-fading-word");
/** Remove a fading word and re-create it with a new start time. */
export const restartFadingWord = (page: Page) => mutateSyntheticBlock(page, "restart-fading-word");
/** Collapse a word whose fade already finished back into plain text. */
export const collapseSettledWord = (page: Page) =>
mutateSyntheticBlock(page, "collapse-settled-word");
/** Re-create the paragraph element with the same text. */
export const replaceParagraph = (page: Page) => mutateSyntheticBlock(page, "replace-paragraph");
/** Re-create the paragraph while carrying its fading word over with the same start time. */
export const replaceParagraphKeepingFadingWord = (page: Page) =>
mutateSyntheticBlock(page, "replace-paragraph-keeping-fading-word");
export async function readMarkdownRootEvidence(page: Page) {
const evidence = await page.evaluate(settleMarkdownRootObserver);
return { replacedElements: evidence.replacedElements, restartedFades: evidence.restartedFades };
}