Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
studio: measure the code block collapse the thread override prevents (#9464)
Daniel Han0f1b989c7306
diff --git a/.github/workflows/studio-frontend-ci.yml b/.github/workflows/studio-frontend-ci.ymlindex 38cadfbfd52..1d4e52b44c3 100644--- a/.github/workflows/studio-frontend-ci.yml+++ b/.github/workflows/studio-frontend-ci.yml@@ -25,6 +25,9 @@ on:- 'tests/studio/probe_dismiss_guard.py'- 'tests/studio/playwright_settings_tabs.py'- 'tests/studio/playwright_stream_pacing.py'+ - 'tests/studio/playwright_code_block_flicker.py'+ - 'tests/studio/_code_block_flicker_analysis.py'+ - 'tests/studio/test_code_block_flicker_contract.py'# Shared lifecycle helpers, and the contract tests that keep verdicts from going unread.- 'tests/studio/_playwright_robust.py'- 'tests/studio/test_autoscroll_harness_contract.py'@@ -367,7 +370,8 @@ jobs:tests/studio/test_autoscroll_harness_contract.py \tests/studio/test_heavy_thread_harness_contract.py \tests/studio/test_heavy_thread_measurement_integrity.py \- tests/studio/test_heavy_thread_gap_contract.py -q+ tests/studio/test_heavy_thread_gap_contract.py \+ tests/studio/test_code_block_flicker_contract.py -q- name: Browser smoke for ANSI tool outputworking-directory: ${{ github.workspace }}@@ -385,6 +389,16 @@ jobs:working-directory: ${{ github.workspace }}run: python3 tests/studio/playwright_research_freeze.py+ # A gate, not a measurement. The released and streamdown variants are positive controls+ # that MUST flicker: a run where neither collapses means the detector stopped seeing, not+ # that the flicker stopped. Chromium only on a PR, the engine whose content-visibility+ # fallback the index.css override exists for.+ - name: Browser smoke for code block flicker+ working-directory: ${{ github.workspace }}+ env:+ SMOKE_FLICKER_ENGINES: chromium+ run: python3 tests/studio/playwright_code_block_flicker.py+# Two small sizes and one repetition on Chromium: enough to prove the fixture still# renders every kind of content it claims to and that the curve still rises, which is all# a PR gate can afford. The measurement this harness exists for is the three-engine,diff --git a/studio/frontend/smoke-code-block-flicker-main.tsx b/studio/frontend/smoke-code-block-flicker-main.tsxnew file mode 100644index 00000000000..69f7ead203c--- /dev/null+++ b/studio/frontend/smoke-code-block-flicker-main.tsx@@ -0,0 +1,510 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Harness page for tests/studio/playwright_code_block_flicker.py: the real Thread, streaming a+// reply that ends in code fences, sampling every code block's rendered HEIGHT per frame.+//+// The mechanism it catches: streamdown sets `content-visibility: auto` with+// `contain-intrinsic-size: auto 200px` inline on every code-block wrapper. Such an element has no+// LAST REMEMBERED SIZE until it has rendered once, so it lays out at the 200px fallback. The+// re-render at the end of a stream REPLACES the node, and a replaced node is new, so it can lay+// out at 200px for a frame before snapping back. That is the "reload" flicker src/index.css+// describes. So the measurement is not a timing: did a TALL block go SHORT and back, and did the+// thread's scrollHeight dip with it -- per frame, the resolution a flicker is visible at.+//+// Same shape as smoke-heavy-thread.html: vite entry, no backend, auth, GPU or model. Thread is+// real because `.aui-thread-root` is where the override lives; a bare ThreadPrimitive.Root lacks+// that class and would report no flicker on every tree.+//+// useLocalRuntime with a generator adapter, not a seeded import: the flicker is at stream+// FINALIZATION, and `thread.import` never passes through the running -> complete transition.++/* eslint-disable no-restricted-imports -- a measurement entry point, not app code. */+// This store first, per smoke-stream-pacing-main.tsx: the renderer's import graph cycles through+// the chat barrel, and entering the cycle from the renderer leaves a constant in its temporal+// dead zone and the harness renders nothing.+import "@/features/chat/stores/sidebar-organization-store";+/* eslint-enable no-restricted-imports */++import { Thread } from "@/components/assistant-ui/thread";+import { TooltipProvider } from "@/components/ui/tooltip";+import {+ AssistantRuntimeProvider,+ type ChatModelAdapter,+ ExportedMessageRepository,+ type ThreadMessageLike,+ useAui,+ useLocalRuntime,+} from "@assistant-ui/react";+import {+ RouterProvider,+ createMemoryHistory,+ createRootRoute,+ createRouter,+} from "@tanstack/react-router";+import { type ReactElement, useEffect } from "react";+import { createRoot } from "react-dom/client";+import "./src/index.css";++// Per smoke-heavy-thread-main.tsx: the fork-count badge fires one GET per assistant message at a+// backend that is not here. Answer before mount, so no round trip lands inside a sampled region.+const realFetch = window.fetch.bind(window);+window.fetch = (input, init) => {+ const url =+ typeof input === "string"+ ? input+ : ((input as Request).url ?? String(input));+ if (url.includes("/api/")) {+ return Promise.resolve(+ new Response("{}", {+ status: 200,+ headers: { "content-type": "application/json" },+ }),+ );+ }+ return realFetch(input, init);+};++// ── CSS variants ────────────────────────────────────────────────────+//+// Each variant is a stylesheet appended AFTER src/index.css, not an edit to the tree. `?css=tree`+// is the pass/fail run; the others exist so "no flicker" can be shown to be a property of the+// tree rather than of the fixture.+//+// The prefix is deliberately OVERSPECIFIC. The tree's rules are scoped+// (`.aui-thread-root[data-status="running"] ...`), so a variant at the obvious specificity loses+// to them exactly where it matters and measures the tree under another name -- that once made+// the pre-override variant report zero flickers, reading as "nothing to fix".+const HERE = ".aui-thread-root.aui-thread-root.aui-thread-root";+const BLOCK = '[data-streamdown="code-block"]';++const CSS_VARIANTS: Record<string, string> = {+ // Whatever src/index.css says, untouched.+ tree: "",+ // Streamdown's defaults, i.e. the tree BEFORE the override. Positive control: this is the state+ // the override prevents, so if it reports no flicker the fixture reproduces nothing and no+ // other row means anything.+ streamdown: `${HERE} ${BLOCK} {+ content-visibility: auto !important;+ contain-intrinsic-size: auto 200px !important;+ }`,+ // The override released for every block at all times, streaming included: the mistake the+ // scoping avoids, and the second positive control, so it MUST flicker too.+ released: `${HERE} ${BLOCK} {+ content-visibility: auto !important;+ contain-intrinsic-size: auto 200px !important;+ }`,+ // The override as main shipped it: visible, and contain-intrinsic-size clobbered to none.+ legacy: `${HERE} ${BLOCK} {+ content-visibility: visible !important;+ contain-intrinsic-size: none !important;+ }`,+ // Streaming status alone, NO settle window: held while the part runs, released the instant it+ // is not. The fix's shape if node replacement at fence close did not land in the same commit+ // as the status flip.+ statusonly: `${HERE} ${BLOCK} {+ content-visibility: auto !important;+ contain-intrinsic-size: auto 200px !important;+ }+ ${HERE} [data-status="running"] ${BLOCK} {+ content-visibility: visible !important;+ }`,+ // Last message only, the CSS-only alternative: no JavaScript, and it survives finalization+ // since the message being finalized is the last. It cannot give an EARLIER message's blocks a+ // first render, so a freshly opened thread holds every off-screen block at the 200px fallback.+ lastmessage: `${HERE} ${BLOCK} {+ content-visibility: auto !important;+ contain-intrinsic-size: auto 200px !important;+ }+ ${HERE} [data-message-id]:not(:has(~ [data-message-id])) ${BLOCK} {+ content-visibility: visible !important;+ }`,+};++const params = new URLSearchParams(window.location.search);+const CSS_MODE = params.get("css") ?? "tree";+const variantCss = CSS_VARIANTS[CSS_MODE];+if (variantCss === undefined) {+ throw new Error(`unknown css variant ${CSS_MODE}`);+}+if (variantCss) {+ const style = document.createElement("style");+ style.dataset.smokeVariant = CSS_MODE;+ // `@layer utilities` is not cosmetic: src/index.css puts the override in that layer, and for+ // IMPORTANT declarations the cascade REVERSES layer order, so a layered `!important` beats an+ // unlayered one however late. Unlayered variants would all lose to the tree and the run would+ // report "no flicker anywhere" having measured one stylesheet four times. Same layer, later in+ // document order, so ordinary precedence applies.+ style.textContent = `@layer utilities { ${variantCss} }`;+ document.head.append(style);+}++// ── content ─────────────────────────────────────────────────────────++const PROSE = [+ "The reception of a long thread is decided by what the renderer does on every interaction rather than by what it did once at load.",+ "A reply that arrives quickly can still leave a thread that answers a keystroke slowly, because the two costs are paid in different places.",+ "Anything that walks the whole message list on each frame turns a pleasant session into an unpleasant one somewhere around the twentieth long answer.",+ "Layout that is not contained propagates upward, so a change inside one message can force the entire column to be measured again.",+];++/** Unique per index: the highlighter caches on the exact source string. */+function fence(index: number, lines: number): string {+ const body = [+ `# block ${index}: a scorer long enough for the highlighter to have real work`,+ ];+ body.push("from dataclasses import dataclass", "");+ for (let i = 0; i < lines; i += 1) {+ body.push(+ `def step_${index}_${i}(rows: list[dict], scale: float = ${(index + i) / 7}) -> float:`,+ ` total = sum(row.get("weight_${i}", 0.0) for row in rows)`,+ ` return total * scale + ${i}.0`,+ "",+ );+ }+ return ["```python", ...body, "```"].join("\n");+}++function prose(index: number, paragraphs: number): string {+ const out: string[] = [];+ for (let i = 0; i < paragraphs; i += 1) {+ out.push(+ `${PROSE[(index + i) % PROSE.length]} (paragraph ${i + 1} of reply ${index})`,+ );+ }+ return out.join("\n\n");+}++/** Settled history: the part of the thread that is NOT streaming while the sample runs. */+function history(messages: number): ThreadMessageLike[] {+ const out: ThreadMessageLike[] = [];+ for (let i = 0; i < messages; i += 1) {+ out.push({+ role: "user",+ content: [{ type: "text", text: `Question ${i}?` }],+ });+ out.push({+ role: "assistant",+ content: [+ {+ type: "text",+ text: [prose(i, 3), fence(i, 14), prose(i + 1, 2)].join("\n\n"),+ },+ ],+ });+ }+ return out;+}++/**+ * The streamed reply. It ENDS in a fence on purpose: the flicker is in "trailing code blocks the+ * moment streaming ends", and a reply ending in prose finalizes with the fence long settled.+ */+function reply(fences: number, linesPerFence: number): string {+ const parts: string[] = [prose(100, 2)];+ for (let i = 0; i < fences; i += 1) {+ parts.push(fence(100 + i, linesPerFence));+ if (i < fences - 1) parts.push(prose(200 + i, 2));+ }+ return parts.join("\n\n");+}++// ── sampling ────────────────────────────────────────────────────────++type Frame = {+ t: number;+ /** Height of every [data-streamdown="code-block"] in DOM order. */+ heights: number[];+ /** Document-space top of each block, i.e. offset within the scroll container's content. */+ tops: number[];+ scrollTop: number;+ scrollHeight: number;+ clientHeight: number;+ /** Viewport-relative top of the last SETTLED assistant message, which must not move. */+ anchorTop: number | null;+ running: boolean;+};++type RunOptions = {+ historyMessages?: number;+ fences?: number;+ linesPerFence?: number;+ chunkChars?: number;+ gapMs?: number;+ /** "bottom" leaves autoscroll pinned; "edge" parks the stream tail at the viewport edge. */+ park?: "bottom" | "edge";+};++const state = {+ cssMode: CSS_MODE,+ frames: [] as Frame[],+ sampling: false,+ streamStartedAt: null as number | null,+ streamEndedAt: null as number | null,+ sentChars: 0,+ done: false,+ error: null as string | null,+};++let config: Required<RunOptions> = {+ historyMessages: 8,+ fences: 3,+ linesPerFence: 22,+ chunkChars: 96,+ gapMs: 8,+ park: "bottom",+};++const sleep = (ms: number) =>+ new Promise((resolve) => {+ setTimeout(resolve, ms);+ });++const adapter: ChatModelAdapter = {+ async *run() {+ const text = reply(config.fences, config.linesPerFence);+ state.streamStartedAt = performance.now();+ let cursor = 0;+ while (cursor < text.length) {+ cursor = Math.min(text.length, cursor + config.chunkChars);+ state.sentChars = cursor;+ yield {+ content: [{ type: "text" as const, text: text.slice(0, cursor) }],+ };+ await sleep(config.gapMs);+ }+ state.streamEndedAt = performance.now();+ },+};++function viewport(): HTMLElement | null {+ return document.querySelector<HTMLElement>(".aui-thread-viewport");+}++function codeBlocks(): HTMLElement[] {+ return Array.from(+ document.querySelectorAll<HTMLElement>(+ '.aui-thread-root [data-streamdown="code-block"]',+ ),+ );+}++/**+ * The last assistant message that existed BEFORE the stream started. Nothing about it changes+ * while the stream runs, so any movement of its top edge is the page shifting under the user.+ * Read in DOCUMENT space (see the analysis module): scrolling must not count as movement.+ */+let anchor: HTMLElement | null = null;++function sample(now: number): void {+ const view = viewport();+ const blocks = codeBlocks();+ const viewRect = view?.getBoundingClientRect();+ const heights: number[] = [];+ const tops: number[] = [];+ for (const block of blocks) {+ heights.push(block.offsetHeight);+ const rect = block.getBoundingClientRect();+ tops.push(+ viewRect ? rect.top - viewRect.top + (view?.scrollTop ?? 0) : rect.top,+ );+ }+ state.frames.push({+ t: now,+ heights,+ tops,+ scrollTop: view?.scrollTop ?? -1,+ scrollHeight: view?.scrollHeight ?? -1,+ clientHeight: view?.clientHeight ?? -1,+ anchorTop: anchor ? anchor.getBoundingClientRect().top : null,+ running: state.streamStartedAt !== null && state.streamEndedAt === null,+ });+}++function FlickerApi(): null {+ const aui = useAui();++ useEffect(() => {+ let handle = 0;+ const loop = (now: number) => {+ if (state.sampling) sample(now);+ // `thread.append` returns void, so completion is read from the runtime. Both halves+ // matter: the generator returning is not the end of the render, and the runtime clearing+ // isRunning is what flips the message to complete.+ if (+ !state.done &&+ state.streamEndedAt !== null &&+ !aui.thread().getState().isRunning+ ) {+ state.done = true;+ }+ handle = requestAnimationFrame(loop);+ };+ handle = requestAnimationFrame(loop);++ const api = {+ cssMode: CSS_MODE,+ /** Settled history only. Returns how many code blocks it produced. */+ seed(messages: number): number {+ aui+ .thread()+ .import(ExportedMessageRepository.fromArray(history(messages)));+ return messages;+ },+ /** Park the viewport where the flicker is meant to be visible. */+ park(mode: "bottom" | "edge"): {+ scrollTop: number;+ scrollHeight: number;+ } {+ const view = viewport();+ if (!view) return { scrollTop: -1, scrollHeight: -1 };+ view.style.scrollBehavior = "auto";+ view.scrollTop =+ mode === "bottom"+ ? view.scrollHeight+ : Math.max(0, view.scrollHeight - view.clientHeight - 240);+ return { scrollTop: view.scrollTop, scrollHeight: view.scrollHeight };+ },+ /** Fix the anchor and start recording. Called once the history has settled. */+ startSampling(): number {+ const assistants = document.querySelectorAll<HTMLElement>(+ '[data-role="assistant"]',+ );+ anchor = assistants[assistants.length - 1] ?? null;+ state.frames = [];+ state.sampling = true;+ return codeBlocks().length;+ },+ stopSampling(): number {+ state.sampling = false;+ return state.frames.length;+ },+ /**+ * Scroll bottom to top, a step per frame pair, while the sampler runs.+ *+ * The half the stream does not answer: a never-rendered block is skipped at the+ * `contain-intrinsic-size` fallback, not at its real height. That shows only on the way+ * back up, as each block expands when reached and pushes what is below it down. Tops are+ * DOCUMENT-space, so a top that moves is content above it being relaid out.+ */+ async sweepUp(+ steps: number,+ stepPx: number,+ ): Promise<Record<string, number>> {+ const view = viewport();+ if (!view) return { steps: 0 };+ view.style.scrollBehavior = "auto";+ view.scrollTop = view.scrollHeight;+ const start = view.scrollTop;+ const twoFrames = () =>+ new Promise<void>((resolve) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));+ });+ await twoFrames();+ for (let i = 0; i < steps && view.scrollTop > 0; i += 1) {+ view.scrollTop = Math.max(0, view.scrollTop - stepPx);+ await twoFrames();+ }+ await twoFrames();+ return {+ steps,+ scrollTopStart: start,+ scrollTopEnd: view.scrollTop,+ scrollHeight: view.scrollHeight,+ };+ },+ run(options: RunOptions = {}): void {+ config = { ...config, ...options };+ state.streamStartedAt = null;+ state.streamEndedAt = null;+ state.sentChars = 0;+ state.done = false;+ state.error = null;+ // From a later task, so the append is not attributed to the caller's task.+ setTimeout(() => {+ try {+ aui+ .thread()+ .append({+ role: "user",+ content: [{ type: "text", text: "stream the fixture" }],+ });+ } catch (err: unknown) {+ state.error = String(err);+ state.done = true;+ }+ }, 0);+ },+ counts(): Record<string, number> {+ return {+ messages: document.querySelectorAll("[data-role]").length,+ codeBlocks: codeBlocks().length,+ preElements: document.querySelectorAll("pre").length,+ highlightedTokens: document.querySelectorAll("pre code span").length,+ domNodes: document.getElementsByTagName("*").length,+ };+ },+ /** What the tree actually computed for a block, so a run says which CSS it measured. */+ computedFor(index: number): Record<string, string> {+ const block = codeBlocks()[index];+ if (!block) return {};+ const style = getComputedStyle(block);+ return {+ contentVisibility: style.contentVisibility,+ containIntrinsicSize: style.containIntrinsicSize,+ layoutAttr:+ document+ .querySelector(".aui-thread-root")+ ?.getAttribute("data-code-block-layout") ?? "(absent)",+ };+ },+ results() {+ return {+ cssMode: state.cssMode,+ frames: state.frames,+ streamStartedAt: state.streamStartedAt,+ streamEndedAt: state.streamEndedAt,+ sentChars: state.sentChars,+ done: state.done,+ error: state.error,+ };+ },+ };+ (window as unknown as { __flicker: typeof api }).__flicker = api;++ return () => {+ cancelAnimationFrame(handle);+ };+ }, [aui]);++ return null;+}++function Harness(): ReactElement {+ const runtime = useLocalRuntime(adapter);+ return (+ <TooltipProvider>+ <AssistantRuntimeProvider runtime={runtime}>+ <FlickerApi />+ <div+ data-smoke="code-block-flicker"+ style={{ display: "flex", flexDirection: "column", height: "100vh" }}+ >+ <Thread hideWelcome={true} />+ </div>+ </AssistantRuntimeProvider>+ </TooltipProvider>+ );+}++const rootRoute = createRootRoute({ component: Harness });+const router = createRouter({+ routeTree: rootRoute,+ history: createMemoryHistory({ initialEntries: ["/"] }),+});++const root = document.getElementById("root");+if (!root) {+ throw new Error("missing #root");+}+createRoot(root).render(<RouterProvider router={router as unknown as never} />);diff --git a/studio/frontend/smoke-code-block-flicker.html b/studio/frontend/smoke-code-block-flicker.htmlnew file mode 100644index 00000000000..ff9e32a7b2b--- /dev/null+++ b/studio/frontend/smoke-code-block-flicker.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <script src="/crypto-boot.js"></script>+ <title>code block flicker smoke</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/smoke-code-block-flicker-main.tsx"></script>+ </body>+</html>diff --git a/studio/frontend/tsconfig.app.json b/studio/frontend/tsconfig.app.jsonindex 732dc02ef2b..bdda66808bb 100644--- a/studio/frontend/tsconfig.app.json+++ b/studio/frontend/tsconfig.app.json@@ -36,6 +36,7 @@"smoke-heavy-thread-main.tsx","smoke-thread-weight-main.tsx","smoke-settings-main.tsx",- "smoke-stream-pacing-main.tsx"+ "smoke-stream-pacing-main.tsx",+ "smoke-code-block-flicker-main.tsx"]}diff --git a/tests/studio/_code_block_flicker_analysis.py b/tests/studio/_code_block_flicker_analysis.pynew file mode 100644index 00000000000..e2aa303eb98--- /dev/null+++ b/tests/studio/_code_block_flicker_analysis.py@@ -0,0 +1,171 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Turning a frame log into "did a code block flicker", separated so it can be tested.++`playwright_code_block_flicker.py` records per frame the rendered height and document-space top of+every `[data-streamdown="code-block"]`. Every pass/fail decision is computed here from those+numbers alone, so it can be exercised against hand-written frame logs without a browser --+including the logs that must NOT be read as a flicker.++Kept out of the harness because that imports playwright, while the contract test has to run+wherever the repo's CPU suite runs.+"""++from __future__ import annotations++# Minimum height before a drop counts, so a genuinely short fence is never read as a collapsed+# tall one.+TALL_PX = 400+# Streamdown's inline fallback is 200px plus the wrapper's padding and header row. A drop landing+# in this band is that fallback specifically, which is what lets a collapse be attributed.+PLACEHOLDER_LO, PLACEHOLDER_HI = 150, 300+# Frames a drop may take to come back. Going short and STAYING short is a different bug.+RECOVERY_FRAMES = 240+# Document-space top movement between two frames of a scroll gesture beyond this is content above+# being relaid out under the user.+SHIFT_PX = 8+++def analyse_stream(frames: list[dict]) -> dict:+ """Collapse-and-recover events over a frame log, per code block.++ Block indices are stable across frames: blocks are only ever APPENDED while a reply streams.++ A collapse is a block at least TALL_PX tall rendering at half that or less and then coming+ back. The recovery is required, so a block legitimately replaced by something shorter, or a+ thread being torn down, is not reported as a flicker.+ """+ collapses = 0+ placeholder_frames = 0+ detail: list[dict] = []+ worst_drop_px = 0.0+ block_count = max((len(f["heights"]) for f in frames), default = 0)++ for index in range(block_count):+ series = [+ (i, f["heights"][index]) for i, f in enumerate(frames) if index < len(f["heights"])+ ]+ open_drop: tuple[int, float] | None = None+ for position in range(1, len(series)):+ frame_index, height = series[position]+ _, previous = series[position - 1]+ if open_drop is None:+ if previous >= TALL_PX and height <= previous * 0.5:+ open_drop = (frame_index, previous)+ worst_drop_px = max(worst_drop_px, previous - height)+ if PLACEHOLDER_LO <= height <= PLACEHOLDER_HI:+ placeholder_frames += 1+ continue+ start_frame, before = open_drop+ # A collapse can deepen after it opens (1700 -> 700 -> 200), so track the worst drop+ # while it stays open. Measuring only the first step reports 1000px for a 1500px+ # collapse and disagrees with the heightAtFloor of the same event.+ worst_drop_px = max(worst_drop_px, before - height)+ if PLACEHOLDER_LO <= height <= PLACEHOLDER_HI:+ placeholder_frames += 1+ if height >= before * 0.9:+ collapses += 1+ detail.append(+ {+ "block": index,+ "fromFrame": start_frame,+ "toFrame": frame_index,+ "heightBefore": before,+ "heightAtFloor": min(+ h for j, h in series if start_frame <= j <= frame_index+ ),+ "frames": frame_index - start_frame,+ }+ )+ open_drop = None+ elif frame_index - start_frame > RECOVERY_FRAMES:+ detail.append(+ {+ "block": index,+ "fromFrame": start_frame,+ "toFrame": None,+ "heightBefore": before,+ "heightAtFloor": height,+ "frames": None,+ }+ )+ open_drop = None++ # A drop still open when the log ends is recorded, not discarded: the ~150 frame tail is+ # shorter than RECOVERY_FRAMES, so a block collapsing at finalization and staying short+ # never trips the branch above and would appear in neither `collapses` nor `detail`.+ # Still not counted as a collapse: it never came back.+ if open_drop is not None:+ start_frame, before = open_drop+ detail.append(+ {+ "block": index,+ "fromFrame": start_frame,+ "toFrame": None,+ "heightBefore": before,+ "heightAtFloor": min(h for j, h in series if j >= start_frame),+ "frames": None,+ }+ )++ dips = 0+ for i in range(1, len(frames)):+ drop = frames[i - 1]["scrollHeight"] - frames[i]["scrollHeight"]+ if drop < 300:+ continue+ for j in range(i + 1, min(i + RECOVERY_FRAMES, len(frames))):+ if frames[j]["scrollHeight"] >= frames[i - 1]["scrollHeight"] - 50:+ dips += 1+ break++ anchor_shift = 0.0+ for i in range(1, len(frames)):+ previous, current = frames[i - 1], frames[i]+ if previous["anchorTop"] is None or current["anchorTop"] is None:+ continue+ # Document space. The viewport scrolling under the anchor is not the anchor moving.+ moved = abs(+ (current["anchorTop"] + current["scrollTop"])+ - (previous["anchorTop"] + previous["scrollTop"])+ )+ anchor_shift = max(anchor_shift, moved)++ return {+ "frames": len(frames),+ "blocks": block_count,+ "collapses": collapses,+ "placeholderFrames": placeholder_frames,+ "scrollHeightDips": dips,+ "anchorShiftPx": round(anchor_shift, 1),+ "worstDropPx": round(worst_drop_px, 1),+ "detail": detail[:12],+ }+++def analyse_sweep(frames: list[dict]) -> dict:+ """Layout shift under a scroll gesture, from the same frame log.++ `tops` is measured from the top of the THREAD'S CONTENT, not the viewport, so scrolling does+ not move it. Anything that does is a block above changing size, which the user sees as the+ page moving under their finger.+ """+ shift_frames = 0+ worst_shift = 0.0+ for i in range(1, len(frames)):+ previous, current = frames[i - 1], frames[i]+ moved = 0.0+ for index in range(min(len(previous["tops"]), len(current["tops"]))):+ moved = max(moved, abs(current["tops"][index] - previous["tops"][index]))+ if moved > SHIFT_PX:+ shift_frames += 1+ worst_shift = max(worst_shift, moved)+ heights = [f["scrollHeight"] for f in frames]+ return {+ "sweepFrames": len(frames),+ "shiftFrames": shift_frames,+ "worstShiftPx": round(worst_shift, 1),+ "scrollHeightMin": min(heights) if heights else -1,+ "scrollHeightMax": max(heights) if heights else -1,+ "scrollHeightGrowthPx": (max(heights) - min(heights)) if heights else -1,+ }diff --git a/tests/studio/playwright_code_block_flicker.py b/tests/studio/playwright_code_block_flicker.pynew file mode 100644index 00000000000..0419f99de66--- /dev/null+++ b/tests/studio/playwright_code_block_flicker.py@@ -0,0 +1,380 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Does a code block flicker through a placeholder height when a stream finalizes?++Streamdown puts `content-visibility: auto` with `contain-intrinsic-size: auto 200px` inline on+every code-block wrapper. Such an element has no LAST REMEMBERED SIZE until it has rendered once,+so until then it lays out at the 200px fallback rather than at its content height. The re-render+at the end of a stream REPLACES the code-block node, and a replaced node is new, so it can lay out+at 200px for a frame and then snap to its real height. That one-frame change is the "reload"+flicker studio/frontend/src/index.css describes, and why the override there exists.++WHAT IS MEASURED++Not a timing. Per frame, for every `[data-streamdown="code-block"]`:++ collapses a block at least 400px tall rendering at half that or less and coming+ back. This is the flicker, and one is too many.+ placeholder frames how many of those landed in the 150-300px band, i.e. on the+ `contain-intrinsic-size` fallback, so a collapse can be attributed.+ scroll height dips the thread's scrollHeight falling 300px or more and recovering: a+ collapsing block takes the whole column with it.+ anchor shift DOCUMENT-space movement of the last message that existed BEFORE the+ stream. Nothing about it changes while the stream runs, so any movement is+ settled content relaid out under the user. Document space is the point:+ viewport-relative would count every scroll as a shift.++Then a second phase on the thread the stream left behind: scroll bottom to top and record whether+the content moved.++ sweep shift frames in which some block's DOCUMENT-space top moved. A never-rendered+ block is skipped at the 200px fallback, not at its real height, which+ shows only on the way back up as each block expands when reached and+ pushes what is below it down.+ scrollHeight grew change in the thread's own height over the gesture. Zero means it was+ already the right height before the sweep.++VARIANTS, AND WHY THE RUN DRIVES MORE THAN ONE++A check that only runs against the tree cannot tell "no flicker" from "the fixture reproduces+nothing". So the fixture is driven under stylesheets appended after the tree's own, and the run+asserts on the SHAPE of the whole set:++ streamdown streamdown's inline defaults, the tree before any override. Positive control:+ this MUST flicker, or the fixture measured nothing and the run fails whatever+ the tree scored.+ released the override released for every block at all times, streaming included: the+ mistake scoping avoids. Second positive control, so it MUST flicker too.+ legacy the override as first written: `content-visibility: visible`,+ `contain-intrinsic-size: none`. Must not flicker.+ tree whatever src/index.css ships now. Must not flicker.+ statusonly held only while the part is running. The obvious CSS-only scoping, measured+ rather than assumed: node replacement at fence close can land in the same commit+ as the status flip, so it still flickers -- hence the tree's settle window.+ lastmessage held only for the last message. Survives finalization but cannot give an earlier+ message's blocks their first render, so it pays in the sweep phase instead.++Neither of the last two decides the exit code; they are here because "the simpler thing does not+work" needs a number next to it.++Run:+ python tests/studio/playwright_code_block_flicker.py+ SMOKE_FLICKER_ENGINES=chromium,webkit python tests/studio/playwright_code_block_flicker.py+ SMOKE_FLICKER_VARIANTS=tree,streamdown python tests/studio/playwright_code_block_flicker.py++It starts and stops its own vite dev server; SMOKE_BASE_URL points it at an existing one and+SMOKE_PORT moves the one it starts. Exits non-zero when a variant that must not flicker did, one+that must flicker did not, or the fixture failed to build the thread it claims to.+"""++from __future__ import annotations++import json+import os+import statistics+import sys+from pathlib import Path++from playwright.sync_api import sync_playwright++sys.path.insert(0, str(Path(__file__).resolve().parent))+from _code_block_flicker_analysis import ( # noqa: E402+ analyse_stream,+ analyse_sweep,+)+from _playwright_robust import ( # noqa: E402+ chromium_launch_args,+ start_vite,+ stop_process,+ wait_for_smoke_page,+)++PORT = int(os.environ.get("SMOKE_PORT", "5219"))+_EXTERNAL = os.environ.get("SMOKE_BASE_URL", "").strip().rstrip("/")+BASE = _EXTERNAL or f"http://127.0.0.1:{PORT}"+OWNS_SERVER = not _EXTERNAL+ENTRY = "smoke-code-block-flicker-main.tsx"+PAGE = "smoke-code-block-flicker.html"+OUT = Path(os.environ.get("PW_ART_DIR", "logs/playwright-code-block-flicker"))+OUT.mkdir(parents = True, exist_ok = True)+LABEL = os.environ.get("SMOKE_LABEL", "tree")++ENGINES = [+ e.strip() for e in os.environ.get("SMOKE_FLICKER_ENGINES", "chromium").split(",") if e.strip()+]+VARIANTS = [+ v.strip()+ for v in os.environ.get("SMOKE_FLICKER_VARIANTS", "tree,legacy,released,streamdown").split(",")+ if v.strip()+]+REPEATS = int(os.environ.get("SMOKE_FLICKER_REPEATS", "3"))+PARK = os.environ.get("SMOKE_FLICKER_PARK", "bottom")++HISTORY_MESSAGES = int(os.environ.get("SMOKE_FLICKER_HISTORY", "8"))+FENCES = int(os.environ.get("SMOKE_FLICKER_FENCES", "3"))+LINES_PER_FENCE = int(os.environ.get("SMOKE_FLICKER_FENCE_LINES", "22"))+CHUNK_CHARS = int(os.environ.get("SMOKE_FLICKER_CHUNK", "96"))+GAP_MS = int(os.environ.get("SMOKE_FLICKER_GAP_MS", "8"))+# Sampling kept alive past `done`: the re-render that causes the flicker lands a frame or two+# after the generator returns, so stopping on `done` stops just short of it.+TAIL_MS = int(os.environ.get("SMOKE_FLICKER_TAIL_MS", "2500"))+++MUST_FLICKER = {"streamdown", "released"}+MUST_NOT_FLICKER = {"tree", "legacy"}++# The positive control is what makes a clean run mean anything: without a variant REQUIRED to+# flicker, "no collapses anywhere" is equally consistent with a detector that measured nothing.+# The verdict loop only judges variants it ran, so a filtered set with no control is refused here.+if not MUST_FLICKER & set(VARIANTS):+ raise SystemExit(+ "SMOKE_FLICKER_VARIANTS="+ + ",".join(VARIANTS)+ + " has no positive control. Include at least one of "+ + ", ".join(sorted(MUST_FLICKER))+ + ", or a run that reports no collapses proves only that nothing was measured."+ )++# What each variant must have computed to on a settled block, checked before anything is measured.+# Without this guard: the tree's override lives in `@layer utilities`, and for IMPORTANT+# declarations the cascade REVERSES layer order, so an unlayered `!important` variant silently+# loses to it. All four then computed `visible`/`none`, all reported zero collapses, and the run+# read as "nothing flickers anywhere" having measured one stylesheet four times.+EXPECTED_COMPUTED = {+ "streamdown": {"contentVisibility": "auto"},+ "released": {"contentVisibility": "auto"},+ "legacy": {"contentVisibility": "visible", "containIntrinsicSize": "none"},+ "statusonly": {"contentVisibility": "auto"},+ "lastmessage": {"contentVisibility": "auto"},+}++# The same guard WHILE THE STREAM IS RUNNING, on the block being streamed. The settled check+# alone is not enough, and that is not hypothetical: the pre-override variant passed it while+# losing the cascade during streaming (the tree only holds while the thread builds, and both agree+# once quiet), then reported zero flickers, reading as "there was never anything to fix".+EXPECTED_COMPUTED_RUNNING = {+ "tree": {"contentVisibility": "visible"},+ "legacy": {"contentVisibility": "visible"},+ "streamdown": {"contentVisibility": "auto"},+ "released": {"contentVisibility": "auto"},+ "statusonly": {"contentVisibility": "visible"},+ "lastmessage": {"contentVisibility": "visible"},+}++SWEEP_STEPS = int(os.environ.get("SMOKE_FLICKER_SWEEP_STEPS", "40"))+SWEEP_STEP_PX = int(os.environ.get("SMOKE_FLICKER_SWEEP_PX", "500"))+++def info(message: str) -> None:+ print(message, flush = True)+++def settle_highlighting(page) -> int:+ """Five stable reads a quarter second apart, the gate PR 9016 had to fix twice.++ Two adjacent reads can land in the lull between async Shiki batches and release the gate on a+ thread that is still building.+ """+ stable = 0+ last = -1+ for _ in range(200):+ count = page.evaluate("window.__flicker.counts().highlightedTokens")+ if count == last and count > 0:+ stable += 1+ if stable >= 5:+ return count+ else:+ stable = 0+ last = count+ page.wait_for_timeout(250)+ raise RuntimeError(f"highlighting never settled (last count {last})")+++def run_case(page, variant: str) -> dict:+ page.goto(f"{BASE}/{PAGE}?css={variant}", wait_until = "domcontentloaded")+ page.wait_for_function("Boolean(window.__flicker)", timeout = 120_000)+ page.evaluate("(n) => window.__flicker.seed(n)", HISTORY_MESSAGES)+ page.wait_for_function(+ "(n) => window.__flicker.counts().messages >= n",+ arg = HISTORY_MESSAGES * 2,+ timeout = 120_000,+ )+ tokens = settle_highlighting(page)+ seeded = page.evaluate("window.__flicker.counts()")+ computed = page.evaluate("window.__flicker.computedFor(0)")+ for prop, want in EXPECTED_COMPUTED.get(variant, {}).items():+ if computed.get(prop) != want:+ raise RuntimeError(+ f"variant {variant}: {prop} computed to {computed.get(prop)!r}, expected {want!r}. "+ "The variant stylesheet did not win the cascade, so this run would have measured "+ "the tree under another name."+ )+ page.evaluate("(m) => window.__flicker.park(m)", PARK)+ page.wait_for_timeout(250)+ blocks_before = page.evaluate("window.__flicker.startSampling()")+ page.evaluate(+ "(o) => window.__flicker.run(o)",+ {+ "historyMessages": HISTORY_MESSAGES,+ "fences": FENCES,+ "linesPerFence": LINES_PER_FENCE,+ "chunkChars": CHUNK_CHARS,+ "gapMs": GAP_MS,+ "park": PARK,+ },+ )+ # Mid-stream cascade guard, on the block being written: the check the settled one cannot make.+ page.wait_for_function("window.__flicker.results().streamStartedAt !== null", timeout = 120_000)+ page.wait_for_timeout(400)+ running_computed = page.evaluate(+ "() => window.__flicker.computedFor(window.__flicker.counts().codeBlocks - 1)"+ )+ still_running = not page.evaluate("window.__flicker.results().done")+ if still_running:+ for prop, want in EXPECTED_COMPUTED_RUNNING.get(variant, {}).items():+ if running_computed.get(prop) != want:+ raise RuntimeError(+ f"variant {variant}: mid-stream {prop} computed to "+ f"{running_computed.get(prop)!r}, expected {want!r}. The rule that should "+ "be in force while a block is streaming is not the one that is."+ )++ page.wait_for_function("window.__flicker.results().done === true", timeout = 300_000)+ page.wait_for_timeout(TAIL_MS)+ page.evaluate("window.__flicker.stopSampling()")+ results = page.evaluate("window.__flicker.results()")+ after = page.evaluate("window.__flicker.counts()")+ if results["error"]:+ raise RuntimeError(f"variant {variant}: stream failed: {results['error']}")+ stats = analyse_stream(results["frames"])++ # Phase two, on the thread the stream left behind: scroll bottom to top, record any movement.+ page.evaluate("window.__flicker.startSampling()")+ sweep_meta = page.evaluate(+ "(a) => window.__flicker.sweepUp(a.steps, a.px)",+ {"steps": SWEEP_STEPS, "px": SWEEP_STEP_PX},+ )+ page.evaluate("window.__flicker.stopSampling()")+ sweep_frames = page.evaluate("window.__flicker.results().frames")+ stats.update(analyse_sweep(sweep_frames))++ stats.update(+ {+ "variant": variant,+ "computed": computed,+ "runningComputed": running_computed,+ "checkedWhileRunning": still_running,+ "seededBlocks": blocks_before,+ "seededTokens": tokens,+ "seeded": seeded,+ "after": after,+ "sentChars": results["sentChars"],+ "sweepMeta": sweep_meta,+ }+ )+ return stats+++def main() -> int:+ proc = None+ if OWNS_SERVER:+ info(f"starting vite dev server on port {PORT}")+ proc = start_vite(PORT)+ failures: list[str] = []+ all_rows: list[dict] = []+ try:+ if OWNS_SERVER:+ wait_for_smoke_page(f"{BASE}/{PAGE}", ENTRY, proc = proc, info = info)+ with sync_playwright() as pw:+ for engine in ENGINES:+ info(f"engine {engine}")+ launcher = getattr(pw, engine)+ browser = (+ launcher.launch(args = chromium_launch_args())+ if engine == "chromium"+ else launcher.launch()+ )+ for variant in VARIANTS:+ for repetition in range(REPEATS):+ page = browser.new_page(viewport = {"width": 1280, "height": 900})+ try:+ row = run_case(page, variant)+ finally:+ page.close()+ row["engine"] = engine+ row["repetition"] = repetition + 1+ all_rows.append(row)+ info(+ f" {engine} {variant} rep {repetition + 1}/{REPEATS}: "+ f"collapses {row['collapses']} placeholder frames "+ f"{row['placeholderFrames']} scrollHeight dips "+ f"{row['scrollHeightDips']} anchor shift {row['anchorShiftPx']}px "+ f"over {row['frames']} frames, {row['blocks']} blocks; "+ f"sweep shift frames {row['shiftFrames']} worst "+ f"{row['worstShiftPx']}px growth {row['scrollHeightGrowthPx']}px"+ )+ browser.close()+ finally:+ if proc is not None:+ stop_process(proc)+ info("vite stopped")++ (OUT / f"{LABEL}.json").write_text(json.dumps(all_rows, indent = 2), encoding = "utf-8")++ info("")+ info(+ f"{'engine':10} {'variant':12} {'collapses':>10} {'placeholder':>12} {'dips':>6} "+ f"{'sweep shift':>12} {'worst px':>9} {'grew px':>9}"+ )+ for engine in ENGINES:+ for variant in VARIANTS:+ rows = [r for r in all_rows if r["engine"] == engine and r["variant"] == variant]+ if not rows:+ continue+ collapses = [r["collapses"] for r in rows]+ info(+ f"{engine:10} {variant:12} {statistics.median(collapses):>10.0f} "+ f"{statistics.median([r['placeholderFrames'] for r in rows]):>12.0f} "+ f"{statistics.median([r['scrollHeightDips'] for r in rows]):>6.0f} "+ f"{statistics.median([r['shiftFrames'] for r in rows]):>12.0f} "+ f"{statistics.median([r['worstShiftPx'] for r in rows]):>9.1f} "+ f"{statistics.median([r['scrollHeightGrowthPx'] for r in rows]):>9.0f}"+ f" per-rep collapses {collapses}"+ )++ if variant in MUST_FLICKER and max(collapses) == 0:+ failures.append(+ f"{engine}/{variant}: no collapse in any of {REPEATS} repetitions. This "+ "variant is the state the override exists to prevent, so the fixture is not "+ "reproducing the flicker and no other row here means anything."+ )+ if variant in MUST_NOT_FLICKER and max(collapses) > 0:+ failures.append(+ f"{engine}/{variant}: {max(collapses)} collapse(s), worst drop "+ f"{max(r['worstDropPx'] for r in rows)}px. A code block rendered at a "+ "fraction of its height and then came back, which is the flicker."+ )+ for row in rows:+ if row["blocks"] < HISTORY_MESSAGES + FENCES:+ failures.append(+ f"{engine}/{variant}: only {row['blocks']} code blocks, expected at "+ f"least {HISTORY_MESSAGES + FENCES}. The fixture did not build."+ )++ info("")+ for row in all_rows[:4]:+ info(f"computed for block 0 under {row['variant']}: {row['computed']}")++ if failures:+ info("")+ for failure in failures:+ info(f"FAIL {failure}")+ return 1+ info("")+ info("every variant behaved as its contract says it must.")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/studio/test_code_block_flicker_contract.py b/tests/studio/test_code_block_flicker_contract.pynew file mode 100644index 00000000000..b5621b97144--- /dev/null+++ b/tests/studio/test_code_block_flicker_contract.py@@ -0,0 +1,311 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""What the code-block flicker harness is held to.++`tests/studio/playwright_code_block_flicker.py` decides whether a code block flickered from a+per-frame log of rendered heights. Two failures there never show up as a failing run: the detector+never fires and every tree looks clean, or it fires on a height change that is not a flicker and+every tree looks broken.++So it is exercised here against hand-written frame logs, including the ones it must NOT report,+and the harness is held to driving at least one variant known to flicker, so a run reporting "no+flicker" has said something.++The analysis lives in `_code_block_flicker_analysis.py` so this file can import it wherever the+CPU suite runs: the harness imports playwright, this does not.+"""++import ast+import sys+from pathlib import Path++import pytest++ROOT = Path(__file__).resolve().parents[2]+STUDIO_TESTS = ROOT / "tests" / "studio"+FRONTEND = ROOT / "studio" / "frontend"+sys.path.insert(0, str(STUDIO_TESTS))++from _code_block_flicker_analysis import ( # noqa: E402+ PLACEHOLDER_HI,+ PLACEHOLDER_LO,+ RECOVERY_FRAMES,+ SHIFT_PX,+ TALL_PX,+ analyse_stream,+ analyse_sweep,+)++HARNESS = STUDIO_TESTS / "playwright_code_block_flicker.py"+FIXTURE = FRONTEND / "smoke-code-block-flicker-main.tsx"+PAGE = FRONTEND / "smoke-code-block-flicker.html"+++def frame(+ heights: list[float],+ scroll_height: float | None = None,+ **overrides,+) -> dict:+ """One sampled frame. Defaults are a still thread: nothing scrolls, nothing moves."""+ base = {+ "t": 0.0,+ "heights": list(heights),+ "tops": [sum(heights[:i]) for i in range(len(heights))],+ "scrollTop": 0.0,+ "scrollHeight": scroll_height if scroll_height is not None else sum(heights),+ "clientHeight": 900.0,+ "anchorTop": 0.0,+ "running": False,+ }+ base.update(overrides)+ return base+++# ── the detector fires on the thing it is for ───────────────────────+++def test_a_one_frame_collapse_to_the_placeholder_is_a_collapse() -> None:+ """The measured shape: 1722px, one frame at 226px, back to 1722px."""+ frames = [frame([1722.0])] * 3 + [frame([226.0])] + [frame([1722.0])] * 3+ result = analyse_stream(frames)+ assert result["collapses"] == 1+ assert result["placeholderFrames"] == 1+ assert result["worstDropPx"] == pytest.approx(1496.0)+ assert result["detail"][0]["heightAtFloor"] == 226.0+ assert result["detail"][0]["frames"] == 1+++def test_a_collapse_that_deepens_reports_its_deepest_point() -> None:+ """A drop arriving over several frames is one collapse, measured at the floor.++ The reported drop must agree with the recorded floor, or a red run understates what it caught:+ 1700 -> 700 -> 200 is a 1500px collapse, not a 1000px one.+ """+ frames = [frame([1700.0]), frame([700.0]), frame([200.0]), frame([1700.0])]+ result = analyse_stream(frames)+ assert result["collapses"] == 1+ assert result["worstDropPx"] == pytest.approx(1500.0)+ assert result["detail"][0]["heightAtFloor"] == 200.0+++def test_each_block_is_counted_separately() -> None:+ """Three fences in one reply collapse one after another, and that is three, not one."""+ tall = [1700.0, 1700.0, 1700.0]+ frames = [frame(tall)] * 2+ for index in range(3):+ collapsed = list(tall)+ collapsed[index] = 226.0+ frames += [frame(collapsed), frame(tall)]+ assert analyse_stream(frames)["collapses"] == 3+++def test_a_collapse_below_the_placeholder_band_still_counts() -> None:+ """`contain-intrinsic-size: auto none` collapses toward zero, not to 200px: a different+ fallback, not a different bug, so it counts but claims no placeholder attribution."""+ frames = [frame([1700.0])] * 2 + [frame([2.0])] + [frame([1700.0])] * 2+ result = analyse_stream(frames)+ assert result["collapses"] == 1+ assert result["placeholderFrames"] == 0+++def test_a_collapsing_block_takes_the_scroll_height_with_it() -> None:+ frames = (+ [frame([1700.0, 1700.0], scroll_height = 3400.0)] * 2+ + [frame([1700.0, 226.0], scroll_height = 1926.0)]+ + [frame([1700.0, 1700.0], scroll_height = 3400.0)] * 2+ )+ assert analyse_stream(frames)["scrollHeightDips"] == 1+++# ── and not on things that are not it ───────────────────────────────+++def test_a_still_thread_reports_nothing() -> None:+ result = analyse_stream([frame([1700.0, 1700.0])] * 40)+ assert result["collapses"] == 0+ assert result["placeholderFrames"] == 0+ assert result["scrollHeightDips"] == 0+ assert result["anchorShiftPx"] == 0.0+++def test_a_block_that_goes_short_and_stays_short_is_not_a_flicker() -> None:+ """A drop with no recovery is a different bug, and reporting it here would hide this one. It+ is still recorded, with a null recovery frame, so it cannot be silently dropped."""+ frames = [frame([1700.0])] * 3 + [frame([226.0])] * (RECOVERY_FRAMES + 5)+ result = analyse_stream(frames)+ assert result["collapses"] == 0+ assert result["detail"], "a drop that never recovered must still be recorded"+ assert result["detail"][0]["toFrame"] is None+++def test_a_drop_still_open_when_the_log_ends_is_recorded() -> None:+ """The tail is shorter than RECOVERY_FRAMES, so the realistic case ends mid-drop.++ 2500ms is ~150 frames at 60Hz against RECOVERY_FRAMES of 240, so a block collapsing at+ finalization and staying short never trips the threshold. It must still appear in `detail`,+ the one place a non-recovering drop is promised to show up.+ """+ frames = [frame([1700.0])] * 3 + [frame([226.0])] * 150+ result = analyse_stream(frames)+ assert result["collapses"] == 0, "it never came back, so it is not a flicker"+ assert result["detail"], "a drop open at the end of the log must still be recorded"+ assert result["detail"][0]["toFrame"] is None+ assert result["detail"][0]["heightAtFloor"] == 226.0+++def test_a_block_growing_as_its_content_arrives_is_not_a_collapse() -> None:+ """A fence gets taller line by line while it streams. Nothing here is a drop."""+ frames = [frame([200.0 * (i + 1)]) for i in range(12)]+ assert analyse_stream(frames)["collapses"] == 0+++def test_a_short_block_is_never_read_as_a_collapsed_tall_one() -> None:+ """A two-line fence really is 120px. Without the floor it would look like a placeholder."""+ assert TALL_PX > PLACEHOLDER_HI+ frames = [frame([TALL_PX - 40.0])] * 2 + [frame([120.0])] + [frame([TALL_PX - 40.0])] * 2+ assert analyse_stream(frames)["collapses"] == 0+++def test_a_thread_that_simply_gets_shorter_is_not_a_dip() -> None:+ """Deleting a message shortens the column and it stays short. That is not a flicker."""+ frames = [frame([1700.0, 1700.0], scroll_height = 3400.0)] * 3 + [+ frame([1700.0], scroll_height = 1700.0)+ ] * 20+ assert analyse_stream(frames)["scrollHeightDips"] == 0+++def test_blocks_appearing_and_disappearing_are_not_collapses() -> None:+ """The heights array is not a fixed-width record: it grows as blocks are APPENDED, and empties+ when the thread unmounts. An absent block has no height, which is not a height of zero:+ reading it as zero turns every teardown into a column of collapses.+ """+ appearing = [frame([1700.0])] * 3 + [frame([1700.0, 900.0])] * 3+ assert analyse_stream(appearing)["collapses"] == 0++ torn_down = [frame([1700.0, 1700.0])] * 3 + [frame([])] * 3 + [frame([1700.0, 1700.0])] * 3+ assert analyse_stream(torn_down)["collapses"] == 0+++def test_scrolling_does_not_move_the_anchor() -> None:+ """The anchor is read in document space, so a scroll of 400px a frame is not a shift."""+ frames = [frame([1700.0], anchorTop = -400.0 * i, scrollTop = 400.0 * i) for i in range(10)]+ assert analyse_stream(frames)["anchorShiftPx"] == 0.0+++def test_content_relaid_out_above_the_anchor_is_a_shift() -> None:+ frames = [+ frame([1700.0], anchorTop = 0.0, scrollTop = 0.0),+ frame([1700.0], anchorTop = -900.0, scrollTop = 0.0),+ ]+ assert analyse_stream(frames)["anchorShiftPx"] == 900.0+++# ── the sweep half ──────────────────────────────────────────────────+++def test_a_sweep_over_a_thread_that_knows_its_own_size_reports_no_shift() -> None:+ tops = [0.0, 1700.0, 3400.0]+ frames = [{"tops": tops, "scrollHeight": 5100.0, "heights": [1700.0] * 3} for _ in range(20)]+ result = analyse_sweep(frames)+ assert result["shiftFrames"] == 0+ assert result["worstShiftPx"] == 0.0+ assert result["scrollHeightGrowthPx"] == 0+++def test_a_block_expanding_as_it_is_reached_moves_everything_below_it() -> None:+ """The placeholder cost, in the phase where the user sees it."""+ before = {"tops": [0.0, 226.0, 452.0], "scrollHeight": 678.0, "heights": [226.0] * 3}+ after = {"tops": [0.0, 1700.0, 1926.0], "scrollHeight": 2152.0, "heights": [1700.0] * 3}+ result = analyse_sweep([before, before, after, after])+ assert result["shiftFrames"] == 1+ assert result["worstShiftPx"] == pytest.approx(1474.0)+ assert result["scrollHeightGrowthPx"] == pytest.approx(1474.0)+++def test_sub_pixel_wobble_is_not_a_shift() -> None:+ """Fractional layout differences are not the page moving under the user."""+ assert SHIFT_PX >= 1+ a = {"tops": [0.0, 1700.0], "scrollHeight": 3400.0, "heights": [1700.0, 1700.0]}+ b = {"tops": [0.0, 1700.4], "scrollHeight": 3400.4, "heights": [1700.0, 1700.4]}+ assert analyse_sweep([a, b])["shiftFrames"] == 0+++# ── the harness itself ──────────────────────────────────────────────+++def harness_source() -> str:+ return HARNESS.read_text(encoding = "utf-8")+++def module_assignment(source: str, name: str) -> ast.expr | None:+ """The value assigned to a module-level `name`, or None.++ Parsed rather than grepped: a substring check passes on a constant renamed to `NAME_DISABLED`+ and left unread, which is how one of these guards gets turned off without a test noticing.+ """+ tree = ast.parse(source)+ for node in tree.body:+ if isinstance(node, ast.Assign):+ for target in node.targets:+ if isinstance(target, ast.Name) and target.id == name:+ return node.value+ return None+++def test_the_run_drives_a_variant_that_is_required_to_flicker() -> None:+ """Without one, "no flicker" cannot be told apart from "measured nothing"."""+ source = harness_source()+ must = module_assignment(source, "MUST_FLICKER")+ must_not = module_assignment(source, "MUST_NOT_FLICKER")+ assert must is not None, "the harness declares no variant that has to flicker"+ assert must_not is not None, "the harness declares no variant that must not flicker"+ assert isinstance(must, ast.Set) and must.elts, "MUST_FLICKER is empty"+ assert isinstance(must_not, ast.Set) and must_not.elts, "MUST_NOT_FLICKER is empty"+ # The exit code has to rest on both halves, not just on the tree behaving.+ verdict = source[source.index("if variant in MUST_FLICKER") :]+ assert "failures.append" in verdict+++def test_a_filtered_variant_set_cannot_drop_every_positive_control() -> None:+ """`SMOKE_FLICKER_VARIANTS=tree` would otherwise pass while proving nothing. The verdict loop+ only judges variants it ran, so a set keeping no MUST_FLICKER member is refused up front."""+ source = harness_source()+ assert (+ "MUST_FLICKER & set(VARIANTS)" in source+ ), "the harness does not check that the selected variants keep a positive control"+ guard = source[source.index("if not MUST_FLICKER & set(VARIANTS)") :]+ assert "raise SystemExit" in guard[:400], "the missing-control check does not stop the run"+++def test_the_fixture_offers_the_state_the_override_was_added_for() -> None:+ """The pre-override stylesheet has to be reachable, or the flicker cannot be reproduced."""+ fixture = FIXTURE.read_text(encoding = "utf-8")+ assert "streamdown:" in fixture+ assert "content-visibility: auto" in fixture+ assert "contain-intrinsic-size: auto 200px" in fixture+++def test_the_variant_stylesheets_are_checked_to_have_won_the_cascade() -> None:+ """A variant that loses to the tree measures the tree under another name. That happened: every+ variant computed identically, all reported zero collapses, and the run read as "nothing to+ fix"."""+ source = harness_source()+ settled = module_assignment(source, "EXPECTED_COMPUTED")+ running = module_assignment(source, "EXPECTED_COMPUTED_RUNNING")+ assert settled is not None and getattr(settled, "keys", None), "no settled cascade check"+ assert running is not None and getattr(+ running, "keys", None+ ), "a settled-state cascade check alone passes on a variant that only loses while streaming"+ assert (+ "EXPECTED_COMPUTED_RUNNING.get(variant" in source+ ), "the mid-stream expectation is declared but never compared against anything"+++def test_the_page_and_its_entry_agree() -> None:+ assert FIXTURE.name in PAGE.read_text(encoding = "utf-8")+++def test_the_placeholder_band_matches_the_fallback_the_library_sets() -> None:+ """200px inline, plus the wrapper's padding and its header row."""+ assert PLACEHOLDER_LO < 200 < PLACEHOLDER_HI