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: collapse the reasoning pane with grid rows instead of a measured height, behind a flag (#9423)
Daniel Han47cacedea8c3
diff --git a/studio/frontend/smoke-collapse-layout-main.tsx b/studio/frontend/smoke-collapse-layout-main.tsxnew file mode 100644index 00000000000..666c0b221bc--- /dev/null+++ b/studio/frontend/smoke-collapse-layout-main.tsx@@ -0,0 +1,250 @@+// 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_collapse_layout.py.+//+// It answers one question: when a collapsible toggles, does the browser lay out the WHOLE document,+// and does that cost scale with how big the document is?+//+// The design point that makes the answer readable is that the COLLAPSIBLE'S OWN CONTENT IS+// IDENTICAL IN EVERY RUN. Only the filler around it changes size. So if a toggle gets more+// expensive as `fillers` grows, the extra cost cannot be the pane's own content -- it is the rest+// of the document being laid out because of a toggle that has nothing to do with it.+//+// Four arms, selected with `?arm=`:+//+// radix-height Radix `CollapsibleContent` + the `animate-collapsible-*` height keyframes.+// Today's mechanism.+// radix-grid Radix `CollapsibleContent` + a `grid-template-rows: 0fr -> 1fr` transition,+// with nothing anywhere reading `--radix-collapsible-content-height`. This is+// the CSS-ONLY version of the fix, and it exists to be disproved: Radix's+// layout effect measures whether or not the variable is consumed, so this arm+// should still force a full-document layout. If it does, a keyframe swap alone+// is not the fix.+// unmeasured-grid The local `UnmeasuredCollapsible` + the same grid transition. No measurement+// at all.+// reasoning The real `ReasoningRoot` / `ReasoningTrigger` / `ReasoningContent` /+// `ReasoningText`, which follow GRID_COLLAPSE_REASONING_ENABLED. Run the page+// once per flag value to get the real before/after rather than a model of it.+//+// No backend, no runtime: the reasoning primitives are plain components, and giving them a+// synthetic runtime would only add nodes that are not part of what is being measured.++import "@/index.css";++// FIRST, and load-bearing. `reasoning.tsx` sits in an import cycle with `markdown-text.tsx` and the+// `@/features/chat` barrel, and `thread.tsx` reads `MarkdownText` at module scope. Entering that+// cycle from `reasoning.tsx` evaluates `thread.tsx` while `markdown-text.tsx` is still+// initialising, and the page dies with "Cannot access 'MarkdownText' before initialization".+// Entering from `thread.tsx`, which is what the app and smoke-heavy-thread.html both do, orders it+// correctly. This is a property of the app's module graph, not of anything under test here.+import "@/components/assistant-ui/thread";++import {+ ReasoningContent,+ ReasoningRoot,+ ReasoningText,+ ReasoningTrigger,+} from "@/components/assistant-ui/reasoning";+import { Collapsible as CollapsiblePrimitive } from "radix-ui";+import {+ UnmeasuredCollapsible,+ UnmeasuredCollapsibleContent,+ UnmeasuredCollapsibleTrigger,+} from "@/components/ui/unmeasured-collapsible";+import type { JSX } from "react";+import { useEffect, useState } from "react";+import { createRoot } from "react-dom/client";++const params = new URLSearchParams(window.location.search);+const arm = params.get("arm") ?? "radix-height";+const fillers = Number.parseInt(params.get("fillers") ?? "0", 10);+const paneParagraphs = Number.parseInt(params.get("paneParagraphs") ?? "40", 10);++const WORDS =+ "the quick brown fox jumps over the lazy dog while a second clause keeps the line long enough to wrap".split(+ " ",+ );++// One filler row is a block with a dozen inline boxes, which is roughly the shape of a line of+// rendered prose. Layout objects, not characters, are the unit that Blink's layout cost is+// proportional to, so the filler is built out of boxes rather than out of one long string.+function Filler({ index }: { index: number }) {+ return (+ <div className="filler-row px-4 py-1 text-sm">+ {WORDS.map((word, i) => (+ <span key={`${word}-${i}`} className="mr-1 inline-block">+ {word}+ {i === 0 ? index : ""}+ </span>+ ))}+ </div>+ );+}++function PaneBody({ extra }: { extra: number }) {+ return (+ <>+ {Array.from({ length: paneParagraphs + extra }, (_, i) => (+ <p key={i} className="mb-2">+ Reasoning paragraph {i}: {WORDS.join(" ")} {WORDS.join(" ")}+ </p>+ ))}+ </>+ );+}++// The two Radix arms use the RAW primitive rather than `@/components/ui/collapsible`, so that the+// class list under test is exactly the one written here. The project wrapper prepends+// `animate-collapsible-down` / `animate-collapsible-up`, and tailwind-merge does not know those as+// members of its `animate` group, so a wrapper-based grid arm would silently keep the height+// keyframes and the comparison would be between two things that both animate height.+//+// `heightContentClass` is `reasoning.tsx`'s own list with the duration inlined.+//+// The two grid arms do NOT share a class string, and the first attempt at this got it wrong in a+// way worth recording. Radix has no "presence separate from state", so its arm has to drive the+// row size off `data-state`. `UnmeasuredCollapsibleContent` drives it off its own staged+// `expanded`, which lags `data-state` by two frames precisely so the `0fr` start value exists.+// Giving the unmeasured arm the `data-[state=open]:grid-rows-[1fr]` variant as well let the+// attribute selector -- higher specificity than the plain class -- win at mount, and the pane+// snapped open with no transition while still reporting a clean layout count. A cheap-looking+// number for an animation that was not running.+const heightContentClass =+ "overflow-hidden ease-out data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down data-[state=closed]:fill-mode-forwards data-[state=open]:duration-200 data-[state=closed]:duration-200";++const radixGridContentClass =+ "grid transition-[grid-template-rows] duration-200 ease-out data-[state=open]:grid-rows-[1fr] data-[state=closed]:grid-rows-[0fr]";++const unmeasuredGridContentClass = "transition-[grid-template-rows] duration-200 ease-out";++function RadixHeightArm({ extra }: ArmProps) {+ return (+ <CollapsiblePrimitive.Root data-probe="collapsible" className="border p-2">+ <CollapsiblePrimitive.Trigger data-probe="trigger">+ toggle+ </CollapsiblePrimitive.Trigger>+ <CollapsiblePrimitive.Content data-probe="content" className={heightContentClass}>+ <PaneBody extra={extra} />+ </CollapsiblePrimitive.Content>+ </CollapsiblePrimitive.Root>+ );+}++function RadixGridArm({ extra }: ArmProps) {+ return (+ <CollapsiblePrimitive.Root data-probe="collapsible" className="border p-2">+ <CollapsiblePrimitive.Trigger data-probe="trigger">+ toggle+ </CollapsiblePrimitive.Trigger>+ <CollapsiblePrimitive.Content data-probe="content" className={radixGridContentClass}>+ <div className="min-h-0 overflow-hidden">+ <PaneBody extra={extra} />+ </div>+ </CollapsiblePrimitive.Content>+ </CollapsiblePrimitive.Root>+ );+}++function UnmeasuredGridArm({ extra }: ArmProps) {+ return (+ <UnmeasuredCollapsible data-probe="collapsible" className="border p-2">+ <UnmeasuredCollapsibleTrigger data-probe="trigger">+ toggle+ </UnmeasuredCollapsibleTrigger>+ <UnmeasuredCollapsibleContent data-probe="content" className={unmeasuredGridContentClass}>+ <PaneBody extra={extra} />+ </UnmeasuredCollapsibleContent>+ </UnmeasuredCollapsible>+ );+}++function ReasoningArm({ extra }: ArmProps) {+ const [open, setOpen] = useState(false);+ return (+ <ReasoningRoot data-probe="collapsible" open={open} onOpenChange={setOpen}>+ <ReasoningTrigger data-probe="trigger" duration={3} />+ <ReasoningContent data-probe="content">+ <ReasoningText>+ <PaneBody extra={extra} />+ </ReasoningText>+ </ReasoningContent>+ </ReasoningRoot>+ );+}++type ArmProps = { extra: number };++const ARMS: Record<string, (props: ArmProps) => JSX.Element> = {+ "radix-height": RadixHeightArm,+ "radix-grid": RadixGridArm,+ "unmeasured-grid": UnmeasuredGridArm,+ reasoning: ReasoningArm,+};++function App() {+ const Arm = ARMS[arm];+ if (!Arm) {+ throw new Error(`unknown arm: ${arm}`);+ }+ // Content streaming into an OPEN pane is the case a height-based collapse gets wrong: the height+ // it animated to was measured once, at toggle time, so content arriving afterwards either+ // overflows the clip or needs a fresh measurement. `1fr` re-resolves every frame, so the driver+ // grows the pane mid-flight and checks the rendered height followed it.+ const [extra, setExtra] = useState(0);+ useEffect(() => {+ (window as unknown as Record<string, unknown>).__probeGrow = (n: number) =>+ setExtra((current) => current + n);+ (window as unknown as Record<string, unknown>).__probeReset = () => setExtra(0);+ }, []);++ // Readiness is published from HERE, after this component and its filler tree have committed,+ // and not from module scope after two frames of the initial render. `createRoot` renders+ // concurrently, so a large `fillers` cell can still be mid-mount two frames in, and a count+ // taken then reports the document as far smaller than it ends up. That number is the x axis of+ // the whole experiment, so getting it from a pre-commit DOM would silently flatten the curve.+ // The frames are still waited out, so the count is taken after layout rather than during it.+ useEffect(() => {+ let inner = 0;+ const outer = requestAnimationFrame(() => {+ inner = requestAnimationFrame(() => {+ (window as unknown as Record<string, unknown>).__probeReady = {+ arm,+ fillers,+ paneParagraphs,+ elements: document.getElementsByTagName("*").length,+ };+ });+ });+ return () => {+ cancelAnimationFrame(outer);+ cancelAnimationFrame(inner);+ };+ }, []);+ return (+ <div>+ {/* The collapsible sits FIRST so that the filler is all after it in document order. A+ full-document layout has to walk it either way; a correctly scoped subtree layout does+ not. */}+ <div data-probe="pane-host">+ <Arm extra={extra} />+ </div>+ <div data-probe="filler-host">+ {Array.from({ length: fillers }, (_, i) => (+ <Filler key={i} index={i} />+ ))}+ </div>+ </div>+ );+}++const root = document.getElementById("root");+if (!root) {+ throw new Error("missing #root");+}++createRoot(root).render(<App />);++// `__probeReady` is published from an effect inside `App` (see above), not from here. At module+// scope the only thing that can be waited on is frames, and frames do not imply that a concurrent+// initial mount has committed.diff --git a/studio/frontend/smoke-collapse-layout.html b/studio/frontend/smoke-collapse-layout.htmlnew file mode 100644index 00000000000..46735711fa0--- /dev/null+++ b/studio/frontend/smoke-collapse-layout.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <script src="/crypto-boot.js"></script>+ <title>collapse layout smoke</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/smoke-collapse-layout-main.tsx"></script>+ </body>+</html>diff --git a/studio/frontend/src/components/assistant-ui/reasoning.tsx b/studio/frontend/src/components/assistant-ui/reasoning.tsxindex b488b1b8aaf..d61f60132eb 100644--- a/studio/frontend/src/components/assistant-ui/reasoning.tsx+++ b/studio/frontend/src/components/assistant-ui/reasoning.tsx@@ -11,6 +11,13 @@ import {CollapsibleContent,CollapsibleTrigger,} from "@/components/ui/collapsible";+import { GRID_COLLAPSE_REASONING_ENABLED } from "@/components/assistant-ui/thread-feature-flags";+import {+ CLOSE_FALLBACK_MARGIN_MS,+ UnmeasuredCollapsible,+ UnmeasuredCollapsibleContent,+ UnmeasuredCollapsibleTrigger,+} from "@/components/ui/unmeasured-collapsible";import {resolveReasoningGroupDuration,resolveReasoningOpen,@@ -77,7 +84,17 @@ function ReasoningRoot({}: ReasoningRootProps) {const collapsibleRef = useRef<HTMLDivElement>(null);const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen);- const lockScroll = useCollapseScrollLock(collapsibleRef, ANIMATION_DURATION);+ // The lock starts in the click handler; the grid transition only starts once React has+ // committed the `0fr` class, so an exact ANIMATION_DURATION releases the scroll container+ // while the row is still shrinking and lets the remaining height change shift the thread.+ // Same margin as the collapse backstop, and only on the grid path: `tool-group` and+ // `tool-fallback` still animate height and keep the plain duration.+ const lockScroll = useCollapseScrollLock(+ collapsibleRef,+ GRID_COLLAPSE_REASONING_ENABLED+ ? ANIMATION_DURATION + CLOSE_FALLBACK_MARGIN_MS+ : ANIMATION_DURATION,+ );const isControlled = controlledOpen !== undefined;const isOpen = isControlled ? controlledOpen : uncontrolledOpen;@@ -95,26 +112,25 @@ function ReasoningRoot({[lockScroll, isControlled, controlledOnOpenChange],);- return (- <Collapsible- ref={collapsibleRef}- data-slot="reasoning-root"- data-variant={variant}- open={isOpen}- onOpenChange={handleOpenChange}- className={cn(- "group/reasoning-root",- reasoningVariants({ variant, className }),- )}- style={- {- "--animation-duration": `${ANIMATION_DURATION}ms`,- } as CSSProperties- }- {...props}- >- {children}- </Collapsible>+ const rootProps = {+ ref: collapsibleRef,+ "data-slot": "reasoning-root",+ "data-variant": variant,+ open: isOpen,+ onOpenChange: handleOpenChange,+ className: cn("group/reasoning-root", reasoningVariants({ variant, className })),+ style: {+ "--animation-duration": `${ANIMATION_DURATION}ms`,+ } as CSSProperties,+ ...props,+ };++ // Same props either way. The only difference is which primitive receives them, and the+ // unmeasured one is a drop-in for the subset of Radix's surface this pane uses.+ return GRID_COLLAPSE_REASONING_ENABLED ? (+ <UnmeasuredCollapsible {...rootProps}>{children}</UnmeasuredCollapsible>+ ) : (+ <Collapsible {...rootProps}>{children}</Collapsible>);}@@ -127,8 +143,12 @@ function ReasoningTrigger({active?: boolean;duration?: number;}) {+ const Trigger = GRID_COLLAPSE_REASONING_ENABLED+ ? UnmeasuredCollapsibleTrigger+ : CollapsibleTrigger;+return (- <CollapsibleTrigger+ <Triggerdata-slot="reasoning-trigger"className={cn("aui-reasoning-trigger group/trigger flex min-w-0 flex-1 cursor-pointer items-center gap-2 py-1 text-muted-foreground text-sm transition-colors hover:text-foreground",@@ -156,7 +176,7 @@ function ReasoningTrigger({"group-data-[state=open]/trigger:rotate-0",)}/>- </CollapsibleTrigger>+ </Trigger>);}@@ -166,16 +186,47 @@ function ReasoningContent({streaming,...props}: ComponentProps<typeof CollapsibleContent> & { streaming?: boolean }) {+ const shared = cn(+ "aui-reasoning-content relative overflow-hidden text-foreground/85 text-ui-13p5 outline-none",+ "group/collapsible-content ease-out",+ "data-[state=closed]:pointer-events-none",+ );++ if (GRID_COLLAPSE_REASONING_ENABLED) {+ return (+ <UnmeasuredCollapsibleContent+ data-slot="reasoning-content"+ closeDurationMs={ANIMATION_DURATION}+ className={cn(+ shared,+ // No `animate-collapsible-*`, so nothing consumes+ // `--radix-collapsible-content-height` and nothing needs to know the content's height.+ // `1fr` resolves against the content on every frame, which is also what makes this+ // correct while reasoning is still streaming into an open pane: the row simply tracks+ // the growing content instead of holding a height captured at toggle time.+ //+ // The duration is unconditional here. The height keyframes needed a per-state duration+ // because they were two different animations; this is one transition run in both+ // directions. `prefers-reduced-motion` still reaches it: index.css forces+ // `transition-duration: 0.01ms !important` on every element, and this is a transition.+ "duration-(--animation-duration)",+ className,+ )}+ {...props}+ >+ {children}+ </UnmeasuredCollapsibleContent>+ );+ }+return (<CollapsibleContentdata-slot="reasoning-content"className={cn(- "aui-reasoning-content relative overflow-hidden text-foreground/85 text-ui-13p5 outline-none",- "group/collapsible-content ease-out",+ shared,"data-[state=closed]:animate-collapsible-up","data-[state=open]:animate-collapsible-down","data-[state=closed]:fill-mode-forwards",- "data-[state=closed]:pointer-events-none","data-[state=open]:duration-(--animation-duration)","data-[state=closed]:duration-(--animation-duration)",className,@@ -391,10 +442,21 @@ const ReasoningGroupImpl: ReasoningGroupComponent = ({// Keep the streaming height cap until the automatic close finishes. Removing// it on the completion frame expands long reasoning to its full height before// the collapsible can close, which makes the entire chat jump.+ //+ // The grid path needs the same margin the collapsible's own backstop uses. The+ // height keyframes animate from a height captured at toggle time, so releasing+ // the cap mid-animation cannot change what they animate; `1fr` instead resolves+ // against the live content every frame, so an early release grows the row in the+ // middle of the collapse and produces exactly the jump this timer prevents. The+ // transition also starts a render after this timer is armed, so an exact+ // ANIMATION_DURATION lands inside it.useEffect(() => {+ const closeDelay = GRID_COLLAPSE_REASONING_ENABLED+ ? ANIMATION_DURATION + CLOSE_FALLBACK_MARGIN_MS+ : ANIMATION_DURATION;const timeout = window.setTimeout(() => setRetainStreamingHeight(isReasoningStreaming),- isReasoningStreaming ? 0 : ANIMATION_DURATION,+ isReasoningStreaming ? 0 : closeDelay,);return () => window.clearTimeout(timeout);}, [isReasoningStreaming]);diff --git a/studio/frontend/src/components/assistant-ui/thread-feature-flags.ts b/studio/frontend/src/components/assistant-ui/thread-feature-flags.tsnew file mode 100644index 00000000000..6755d0a531e--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/thread-feature-flags.ts@@ -0,0 +1,29 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Thread feature flags for staged rollout. The wiring stays in place so flipping a flag here is+// the only edit needed to re-enable.++// Grid-based reasoning collapse: the reasoning pane opens and closes by transitioning+// `grid-template-rows` from `0fr` to `1fr` instead of animating `height` from `0` to+// `--radix-collapsible-content-height`, and it uses a local collapsible primitive that never calls+// `getBoundingClientRect`.+//+// Both halves are required. The CSS variable is supplied by Radix's `CollapsibleContentImpl`,+// whose `useLayoutEffect` writes `transitionDuration: 0s` / `animationName: none`, reads+// `getBoundingClientRect()`, then writes the styles back -- on every `open` change,+// UNCONDITIONALLY, whether or not any stylesheet consumes the variable it produces. That read is a+// synchronous full-document layout, and Blink's layout is O(total layout objects) rather than+// O(dirty objects), so it is charged the whole thread. Swapping only the keyframes leaves the+// measurement exactly where it was; see `unmeasured-collapsible.tsx`.+//+// Scoped to the reasoning pane. `tool-group.tsx`, `tool-fallback.tsx` and the shared+// `components/ui/collapsible.tsx` default still animate height: `app-sidebar.tsx` keys its scroll+// fade off `onAnimationEnd` with `animationName === "collapsible-down" | "collapsible-up"`, which a+// transition does not fire, and changing three collapsibles at once would make an A/B on the+// reasoning toggle unattributable.+//+// OFF until the A/B has run. CONTRIBUTING-perf.md is explicit that a direction is not a result, and+// this one also changes the rendered DOM (one wrapper element inside the content), so it needs+// screenshots as well as the parity digest.+export const GRID_COLLAPSE_REASONING_ENABLED = false;diff --git a/studio/frontend/src/components/ui/unmeasured-collapsible.tsx b/studio/frontend/src/components/ui/unmeasured-collapsible.tsxnew file mode 100644index 00000000000..17e9db903f3--- /dev/null+++ b/studio/frontend/src/components/ui/unmeasured-collapsible.tsx@@ -0,0 +1,294 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// A collapsible that never measures its content.+//+// WHY THIS EXISTS, and why swapping the keyframes alone would not have worked.+//+// Radix's `CollapsibleContentImpl` runs this on every `open` change (react-collapsible 1.1.12,+// dist/index.mjs, verbatim shape):+//+// useLayoutEffect(() => {+// const node = ref.current;+// if (node) {+// node.style.transitionDuration = "0s"; // write+// node.style.animationName = "none"; // write+// const rect = node.getBoundingClientRect();// READ -> synchronous layout+// heightRef.current = rect.height;+// widthRef.current = rect.width;+// ... // write back+// }+// }, [context.open, present]);+//+// It publishes the result as `--radix-collapsible-content-height`, which the+// `animate-collapsible-down` / `animate-collapsible-up` keyframes consume. The read is+// UNCONDITIONAL: it does not check whether any stylesheet references the variable. So replacing the+// height keyframes with a `grid-template-rows: 0fr -> 1fr` transition removes the CONSUMER of the+// measurement and leaves the measurement itself untouched. The forced layout stays, and with it the+// full-document relayout that Blink charges for it, because Blink's layout is O(total layout+// objects) and not O(dirty objects).+//+// Hence a local primitive. It keeps Radix's public shape -- `data-state`, `data-disabled`,+// `aria-expanded`, `aria-controls`, the generated content id, `hidden` when closed, and children+// unmounted while closed -- and drops only the measurement, because with `0fr -> 1fr` there is+// nothing left to measure: `1fr` resolves against the content on its own, every frame, including+// while the content is still streaming in.+//+// Two things the grid technique requires, and it silently does not collapse without them:+// * the animating child must be `min-height: 0`, or its automatic minimum size floors the row at+// the content's height and `0fr` never reaches zero;+// * it must be `overflow: hidden`, or the content paints outside the zero-height row.+// Both live on the wrapper this component renders, not on the caller's node, so a caller cannot+// forget them. That wrapper is one element more than Radix renders, which is a real DOM difference+// and is why the flag that selects this path also needs screenshots, not just the parity digest.++import { cn } from "@/lib/utils";+import * as React from "react";++type UnmeasuredCollapsibleContextValue = {+ open: boolean;+ disabled?: boolean;+ contentId: string;+ onOpenToggle: () => void;+};++const UnmeasuredCollapsibleContext =+ React.createContext<UnmeasuredCollapsibleContextValue | null>(null);++function useUnmeasuredCollapsibleContext(consumer: string) {+ const context = React.useContext(UnmeasuredCollapsibleContext);+ if (!context) {+ throw new Error(`\`${consumer}\` must be used within \`UnmeasuredCollapsible\``);+ }+ return context;+}++function getState(open: boolean) {+ return open ? "open" : "closed";+}++type UnmeasuredCollapsibleProps = Omit<+ React.ComponentPropsWithoutRef<"div">,+ "onToggle"+> & {+ open?: boolean;+ defaultOpen?: boolean;+ disabled?: boolean;+ onOpenChange?: (open: boolean) => void;+};++const UnmeasuredCollapsible = React.forwardRef<+ HTMLDivElement,+ UnmeasuredCollapsibleProps+>(+ (+ {+ open: openProp,+ defaultOpen = false,+ disabled,+ onOpenChange,+ children,+ ...props+ },+ forwardedRef,+ ) => {+ const [uncontrolledOpen, setUncontrolledOpen] = React.useState(defaultOpen);+ const isControlled = openProp !== undefined;+ const open = isControlled ? openProp : uncontrolledOpen;+ const contentId = React.useId();++ // Closes over the committed `open`, and deliberately not over a ref written during+ // render. A render can be abandoned or suspended, and React does not roll a ref back when+ // that happens, so a ref assigned here can hold a value that was never committed while the+ // trigger the user is looking at still shows the old one; the click would then toggle away+ // from the visible state. The ref bought nothing anyway: `context` below is memoized on+ // `open`, so it is rebuilt on every open change whatever this callback's identity is.+ const onOpenToggle = React.useCallback(() => {+ const next = !open;+ if (!isControlled) {+ setUncontrolledOpen(next);+ }+ onOpenChange?.(next);+ }, [open, isControlled, onOpenChange]);++ const context = React.useMemo<UnmeasuredCollapsibleContextValue>(+ () => ({ open, disabled, contentId, onOpenToggle }),+ [open, disabled, contentId, onOpenToggle],+ );++ return (+ <UnmeasuredCollapsibleContext.Provider value={context}>+ <div+ data-slot="collapsible"+ data-state={getState(open)}+ data-disabled={disabled ? "" : undefined}+ {...props}+ ref={forwardedRef}+ >+ {children}+ </div>+ </UnmeasuredCollapsibleContext.Provider>+ );+ },+);+UnmeasuredCollapsible.displayName = "UnmeasuredCollapsible";++const UnmeasuredCollapsibleTrigger = React.forwardRef<+ HTMLButtonElement,+ React.ComponentPropsWithoutRef<"button">+>(({ onClick, ...props }, forwardedRef) => {+ const context = useUnmeasuredCollapsibleContext("UnmeasuredCollapsibleTrigger");+ return (+ <button+ type="button"+ aria-controls={context.contentId}+ aria-expanded={context.open || false}+ data-slot="collapsible-trigger"+ data-state={getState(context.open)}+ data-disabled={context.disabled ? "" : undefined}+ disabled={context.disabled}+ {...props}+ ref={forwardedRef}+ onClick={(event) => {+ onClick?.(event);+ if (!event.defaultPrevented) {+ context.onOpenToggle();+ }+ }}+ />+ );+});+UnmeasuredCollapsibleTrigger.displayName = "UnmeasuredCollapsibleTrigger";++type UnmeasuredCollapsibleContentProps = React.ComponentPropsWithoutRef<"div"> & {+ // Upper bound on how long the caller's `grid-template-rows` transition can run. Children unmount+ // when the transition ends; this is the fallback for the cases where `transitionend` never+ // arrives -- a closed pane inside a `display: none` ancestor, a tab in the background, or+ // reduced motion collapsing the duration to 0.01ms in a browser that then skips the event.+ // The timer is armed at this plus `CLOSE_FALLBACK_MARGIN_MS`, so it stays a fallback rather+ // than the path that normally wins.+ closeDurationMs?: number;+ // Rendered even while closed. Matches Radix's `forceMount`, and like Radix's it exists so a+ // caller can drive its own presence.+ forceMount?: boolean;+};++const DEFAULT_CLOSE_DURATION_MS = 200;++// The backstop is armed in the same passive-effect flush that queues `setExpanded(false)`, so its+// countdown starts before React commits the `0fr` class and before the browser starts the+// transition. Armed at exactly `closeDurationMs` it would therefore always win the race it is+// supposed to lose, unmounting the children a few milliseconds early -- and more than that when a+// busy main thread delays the commit. The margin puts it back behind `transitionend`.+export const CLOSE_FALLBACK_MARGIN_MS = 50;++const UnmeasuredCollapsibleContent = React.forwardRef<+ HTMLDivElement,+ UnmeasuredCollapsibleContentProps+>(+ (+ {+ className,+ children,+ closeDurationMs = DEFAULT_CLOSE_DURATION_MS,+ forceMount,+ ...props+ },+ forwardedRef,+ ) => {+ const context = useUnmeasuredCollapsibleContext("UnmeasuredCollapsibleContent");+ const open = context.open;++ // `mounted` is presence: true from the moment the pane starts opening until the close+ // transition has finished, so the content is still there to animate out.+ // `expanded` is the row size: it drives `0fr` vs `1fr`.+ const [mounted, setMounted] = React.useState(open);+ const [expanded, setExpanded] = React.useState(open);+ const nodeRef = React.useRef<HTMLDivElement>(null);+ const composedRef = React.useCallback(+ (node: HTMLDivElement | null) => {+ nodeRef.current = node;+ if (typeof forwardedRef === "function") {+ forwardedRef(node);+ } else if (forwardedRef) {+ forwardedRef.current = node;+ }+ },+ [forwardedRef],+ );++ // Opening: mount at `0fr` first, then flip to `1fr` once the browser has computed a style for+ // the mounted node. Two frames, because a class change in the same frame as the insertion has+ // no before-change style to transition FROM and would snap open. This costs one frame of+ // animation start, never a layout read.+ React.useEffect(() => {+ if (open) {+ setMounted(true);+ let inner = 0;+ const outer = requestAnimationFrame(() => {+ inner = requestAnimationFrame(() => setExpanded(true));+ });+ return () => {+ cancelAnimationFrame(outer);+ cancelAnimationFrame(inner);+ };+ }+ setExpanded(false);+ return undefined;+ }, [open]);++ // Closing: unmount the children when the row has finished shrinking. `transitionend` bubbles+ // from descendants and fires once per property, so both are filtered; the timeout is the+ // backstop described on `closeDurationMs`.+ React.useEffect(() => {+ if (open || !mounted) {+ return undefined;+ }+ const node = nodeRef.current;+ const finish = () => setMounted(false);+ const onTransitionEnd = (event: TransitionEvent) => {+ if (event.target === node && event.propertyName === "grid-template-rows") {+ finish();+ }+ };+ node?.addEventListener("transitionend", onTransitionEnd);+ const timeout = window.setTimeout(finish, closeDurationMs + CLOSE_FALLBACK_MARGIN_MS);+ return () => {+ node?.removeEventListener("transitionend", onTransitionEnd);+ window.clearTimeout(timeout);+ };+ }, [open, mounted, closeDurationMs]);++ const present = forceMount || mounted;++ return (+ <div+ data-slot="collapsible-content"+ data-state={getState(open)}+ data-disabled={context.disabled ? "" : undefined}+ id={context.contentId}+ hidden={!present}+ {...props}+ ref={composedRef}+ className={cn(+ // `hidden` alone would not hide this: the UA sheet's `[hidden] { display: none }` loses+ // to any author `display`, and `grid` is an author declaration. So the closed state+ // switches the display utility itself rather than relying on the attribute.+ present ? "grid" : "hidden",+ "transition-[grid-template-rows]",+ expanded ? "grid-rows-[1fr]" : "grid-rows-[0fr]",+ className,+ )}+ >+ <div className="min-h-0 overflow-hidden">{present && children}</div>+ </div>+ );+ },+);+UnmeasuredCollapsibleContent.displayName = "UnmeasuredCollapsibleContent";++export {+ UnmeasuredCollapsible,+ UnmeasuredCollapsibleContent,+ UnmeasuredCollapsibleTrigger,+};diff --git a/studio/frontend/tests/reasoning-grid-collapse.test.ts b/studio/frontend/tests/reasoning-grid-collapse.test.tsnew file mode 100644index 00000000000..bab6bff175b--- /dev/null+++ b/studio/frontend/tests/reasoning-grid-collapse.test.ts@@ -0,0 +1,215 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Source-pinned, following the convention the other .tsx tests here use: node's type stripping+// cannot compile JSX, so a component in a .tsx file is pinned by reading it.+//+// Everything asserted below is something whose absence produces a pane that LOOKS fine in a+// screenshot and is wrong:+//+// * a measurement anywhere in the unmeasured primitive puts the forced layout straight back,+// and the change then costs a wrapper element and buys nothing;+// * `min-height: 0` or `overflow: hidden` missing from the animating child means `0fr` never+// reaches zero and the pane does not close;+// * the height keyframes surviving on the flag-on path means both mechanisms run at once;+// * the keyframes DISAPPEARING from the shared collapsible breaks `app-sidebar.tsx`, which keys+// its scroll fade off `animationName === "collapsible-down" | "collapsible-up"` and would go+// silently stale.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++const read = (path: string) =>+ readFileSync(new URL(path, import.meta.url), "utf8");++const UNMEASURED = read("../src/components/ui/unmeasured-collapsible.tsx");+const REASONING = read("../src/components/assistant-ui/reasoning.tsx");+const FLAGS = read("../src/components/assistant-ui/thread-feature-flags.ts");+const SHARED_COLLAPSIBLE = read("../src/components/ui/collapsible.tsx");+const APP_SIDEBAR = read("../src/components/app-sidebar.tsx");+const TOOL_GROUP = read("../src/components/assistant-ui/tool-group.tsx");+const TOOL_FALLBACK = read("../src/components/assistant-ui/tool-fallback.tsx");++// Comments in these files discuss measurement at length, so an assertion on the raw text would+// pass or fail on prose. Only code lines are considered.+function codeOf(source: string): string {+ return source+ .split("\n")+ .filter((line) => {+ const trimmed = line.trim();+ return (+ trimmed.length > 0 &&+ !trimmed.startsWith("//") &&+ !trimmed.startsWith("*") &&+ !trimmed.startsWith("/*")+ );+ })+ .join("\n");+}++test("the unmeasured collapsible reads no geometry at all", () => {+ const code = codeOf(UNMEASURED);+ for (const api of [+ "getBoundingClientRect",+ "getComputedStyle",+ "offsetHeight",+ "offsetWidth",+ "clientHeight",+ "clientWidth",+ "scrollHeight",+ "scrollWidth",+ "getClientRects",+ "ResizeObserver",+ ]) {+ assert.ok(+ !code.includes(api),+ `unmeasured-collapsible.tsx must not use ${api}; that is the whole point of it`,+ );+ }+});++test("the animating child carries min-height:0 and overflow:hidden", () => {+ // Both on one element, and that element is the wrapper the component renders itself, so a+ // caller cannot omit them.+ assert.match(UNMEASURED, /className="min-h-0 overflow-hidden"/);+});++test("the collapse is a grid-template-rows transition between 0fr and 1fr", () => {+ const code = codeOf(UNMEASURED);+ assert.ok(code.includes("transition-[grid-template-rows]"));+ assert.ok(code.includes('"grid-rows-[1fr]"'));+ assert.ok(code.includes('"grid-rows-[0fr]"'));+ // The closed state must switch the display utility, not lean on the `hidden` attribute: the UA+ // sheet's `[hidden] { display: none }` loses to the author-level `display: grid`.+ assert.ok(code.includes('present ? "grid" : "hidden"'));+});++test("the unmeasured trigger keeps the accessible collapsible contract", () => {+ const code = codeOf(UNMEASURED);+ assert.ok(code.includes("aria-expanded={context.open || false}"));+ assert.ok(code.includes("aria-controls={context.contentId}"));+ assert.ok(code.includes('type="button"'));+ // Content must carry the id the trigger points at, or aria-controls dangles.+ assert.ok(code.includes("id={context.contentId}"));+ // data-state is what every consumer's `data-[state=...]` and `group-data-[state=...]` class+ // keys off, on the root, the trigger and the content alike.+ assert.equal(code.match(/data-state=\{getState\(/g)?.length, 3);+});++test("children unmount while closed, exactly as Radix's presence does", () => {+ const code = codeOf(UNMEASURED);+ assert.ok(code.includes("{present && children}"));+ // Keeping a closed pane's content mounted would grow the resting DOM of a long thread, which is+ // the opposite of what this change is for.+ assert.ok(code.includes("setMounted(false)"));+});++test("the close path unmounts on transitionend for the right property, with a timeout backstop", () => {+ const code = codeOf(UNMEASURED);+ // transitionend bubbles from descendants and fires once per property; an unfiltered handler+ // would unmount the content the first time anything inside it finished any transition.+ assert.ok(+ code.includes('event.target === node && event.propertyName === "grid-template-rows"'),+ );+ // The backstop must be armed BEYOND the transition duration. It starts counting in the same+ // passive-effect flush that queues `setExpanded(false)`, which is before the browser starts the+ // transition, so arming it at exactly `closeDurationMs` makes it always beat `transitionend` and+ // cut the close short.+ assert.ok(+ code.includes("window.setTimeout(finish, closeDurationMs + CLOSE_FALLBACK_MARGIN_MS)"),+ );+ assert.match(code, /const CLOSE_FALLBACK_MARGIN_MS = \d+;/);+});++test("nothing writes a ref during render", () => {+ const code = codeOf(UNMEASURED);+ // React does not roll a ref back when a render is abandoned or suspended, so a ref+ // assigned in the render body can hold a value that was never committed while the DOM+ // still shows the old one. The toggle closes over `open` instead. (`nodeRef` is written+ // inside the ref callback, which runs on commit, not during render.)+ assert.ok(!code.includes("openRef"));+ assert.ok(code.includes("const next = !open;"));+});++test("the flag is off by default", () => {+ assert.match(FLAGS, /export const GRID_COLLAPSE_REASONING_ENABLED = false;/);+});++test("the reasoning pane picks its primitive from the flag on all three slots", () => {+ const code = codeOf(REASONING);+ // Three primitive slots, plus the streaming-height release and the scroll lock, which both+ // have to outlast the transition rather than the nominal duration.+ assert.equal(code.match(/GRID_COLLAPSE_REASONING_ENABLED/g)?.length, 6);+ assert.ok(code.includes("<UnmeasuredCollapsible {...rootProps}>"));+ assert.ok(code.includes("<Collapsible {...rootProps}>"));+ assert.ok(code.includes("UnmeasuredCollapsibleTrigger"));+ assert.ok(code.includes("<UnmeasuredCollapsibleContent"));+});++test("the streaming height cap outlives the grid collapse, but only on the grid path", () => {+ const code = codeOf(REASONING);+ // `1fr` resolves against live content every frame, so releasing `max-h-64` before the row has+ // finished shrinking grows it mid-collapse -- the jump the retention timer exists to prevent.+ // The height keyframes animate a height captured at toggle time, so the default path is immune+ // and must keep its exact ANIMATION_DURATION.+ assert.ok(+ code.includes("ANIMATION_DURATION + CLOSE_FALLBACK_MARGIN_MS"),+ );+ assert.ok(code.includes("const closeDelay = GRID_COLLAPSE_REASONING_ENABLED"));+});++test("the scroll lock outlasts the grid collapse, and the shared hook's other callers do not move", () => {+ const code = codeOf(REASONING);+ // The lock is armed in the click handler, a commit before the transition starts, so an exact+ // ANIMATION_DURATION releases the container mid-collapse.+ assert.match(+ code,+ /useCollapseScrollLock\(\s*collapsibleRef,\s*GRID_COLLAPSE_REASONING_ENABLED/,+ );+ // tool-group and tool-fallback share the hook but keep the height keyframes, so they must+ // still pass the plain duration.+ for (const other of [TOOL_GROUP, TOOL_FALLBACK]) {+ assert.ok(+ codeOf(other).includes("useCollapseScrollLock(collapsibleRef, ANIMATION_DURATION)"),+ );+ }+});++test("the flag-on reasoning content runs no height keyframes", () => {+ // Split at the flag branch: everything before the `return` of the flag-off path is the grid+ // path, and the height keyframes must appear only after it.+ const gridBranch = REASONING.slice(+ REASONING.indexOf("if (GRID_COLLAPSE_REASONING_ENABLED) {"),+ REASONING.indexOf("</UnmeasuredCollapsibleContent>"),+ );+ assert.ok(gridBranch.length > 0);+ assert.ok(!gridBranch.includes("animate-collapsible-up"));+ assert.ok(!gridBranch.includes("animate-collapsible-down"));+ // and the flag-off path is untouched, so flag-off is byte-identical behaviour.+ assert.ok(REASONING.includes('"data-[state=closed]:animate-collapsible-up"'));+ assert.ok(REASONING.includes('"data-[state=open]:animate-collapsible-down"'));+});++test("the height keyframes stay in use everywhere else, because the sidebar listens for them", () => {+ assert.ok(SHARED_COLLAPSIBLE.includes("animate-collapsible-down"));+ assert.ok(SHARED_COLLAPSIBLE.includes("animate-collapsible-up"));+ assert.ok(TOOL_GROUP.includes("animate-collapsible-down"));+ assert.ok(TOOL_FALLBACK.includes("animate-collapsible-down"));+ assert.ok(APP_SIDEBAR.includes('e.animationName === "collapsible-down"'));+ assert.ok(APP_SIDEBAR.includes('e.animationName === "collapsible-up"'));+});++test("reduced motion is reached by the transition, not bypassed by it", () => {+ const indexCss = read("../src/index.css");+ // Two blankets, the OS media query and the in-app override class. Both force+ // transition-duration as well as animation-duration, which is what makes a transition-based+ // collapse honour reduced motion without any new rule.+ assert.ok(indexCss.includes("html.force-reduced-motion *"));+ assert.ok(indexCss.includes("@media (prefers-reduced-motion: reduce)"));+ assert.equal(+ indexCss.match(/transition-duration: 0\.01ms !important;/g)?.length,+ 2,+ "both reduced-motion blankets must force transition-duration, not only animation-duration",+ );+});diff --git a/tests/studio/playwright_collapse_layout.py b/tests/studio/playwright_collapse_layout.pynew file mode 100644index 00000000000..dae69b86f3e--- /dev/null+++ b/tests/studio/playwright_collapse_layout.py@@ -0,0 +1,845 @@+# 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 a collapsible toggle costs, and why that cost is a property of the WHOLE document.++Radix's `CollapsibleContentImpl` runs a layout effect on every `open` change that writes+`transitionDuration: 0s` and `animationName: none`, reads `getBoundingClientRect()`, then writes+the styles back. The read is a synchronous layout, and it is UNCONDITIONAL: it does not ask+whether any stylesheet consumes the `--radix-collapsible-content-height` it publishes. Blink's+layout is O(total layout objects) rather than O(dirty objects), so that one read is charged for+walking the entire document, not the pane that changed.++This drives studio/frontend/smoke-collapse-layout.html, whose design point is that THE PANE'S OWN+CONTENT IS IDENTICAL IN EVERY RUN. Only the filler around it changes size. So a toggle that gets+more expensive as `fillers` grows cannot be paying for the pane, and the extra cost has nowhere to+come from except the rest of the document.++The four arms and what each is for:++ radix-height Radix content plus the `animate-collapsible-*` height keyframes. Today's+ mechanism, and the baseline the other three are read against.+ radix-grid Radix content plus a `grid-template-rows: 0fr -> 1fr` transition, with nothing+ consuming `--radix-collapsible-content-height`. This arm exists TO BE+ DISPROVED. If it forces the same full-document layout as radix-height, then+ swapping the keyframes is not the fix, because the measurement Radix does is+ not conditional on anything reading its result.+ unmeasured-grid The local `UnmeasuredCollapsible` plus the same grid transition, and no+ measurement at all. This is the arm that should not scale.+ reasoning The real reasoning primitives, which follow GRID_COLLAPSE_REASONING_ENABLED.+ Run the page once per flag value for the real before/after rather than a+ model of it; the flag is a build-time constant, so this driver records the+ value it found in the checkout it served rather than choosing one.++The documented expectation, stated here as what the arms are FOR and deliberately NOT asserted+below: radix-height and radix-grid both force the full-document layout, unmeasured-grid does not.++Two independent numbers are collected per cell, because each covers the other's blind spot:++ tracing `Layout` trace events carry `args.beginData.dirtyObjects`, `totalObjects` and+ `partialLayout` alongside the event's own duration, which is the only place+ the "milliseconds of layout for a handful of dirty objects against a+ six-figure tree" shape is visible at all.+ Performance `Performance.getMetrics` before and after the toggles gives `LayoutCount` and+ `LayoutDuration`, which are cheap, stable, and cannot be thrown off by a+ trace category being renamed upstream. If the two disagree, the trace parse+ is the side to suspect.++READ THE FORCED COLUMN, NOT THE TOTAL. Both mechanisms animate a property that layout depends on,+`height` on one side and `grid-template-rows` on the other, so both lay out on every animation+frame and the raw layout count mostly counts frames. What separates the arms is the layout Blink+did SYNCHRONOUSLY because script asked for a geometry it had invalidated, and the trace names those+exactly: only a script-forced layout carries `args.beginData.stackTrace`, and on the Radix arms+that stack reads `commitHookLayoutEffects` into the collapsible's `getBoundingClientRect`. The+report keeps both, and the forced count is the one the arms differ on.++One property of the page worth knowing before reading its radix-grid row: that arm barely animates.+Radix's presence machinery keys off animation events, and the arm has only a transition, so the+pane unmounts immediately on close and mounts already at `1fr` on open. Its total layout count is+therefore small for a reason that has nothing to do with the measurement, which is a second reason+to read the forced column there.++The last thing each cell does is grow the content of an OPEN pane and check that the rendered+height followed it, which is the case a height captured at toggle time gets wrong and `1fr` gets+right by construction. Note what that check can and cannot see here: the height keyframes carry+`fill-mode-forwards` only on close, so once the open animation ends the pane is back to its+natural height and growth after that point is followed on every arm. The clipping this looks for+is what a captured height that OUTLIVED its animation would produce, so a clean row is the+expected reading and a dirty one is a real regression, not the other way round.++There is no performance budget here on purpose. This is a measurement probe, and layout timings+vary by more across machines than the effect being measured varies across a healthy tree, so a+hard threshold would be flaky in CI and would be tuned away rather than fixed. It exits non-zero+only for a harness failure: a page that never became ready, an arm that rendered nothing, a filler+parameter that was ignored, a trace that captured no layouts at all.++Run:+ python tests/studio/playwright_collapse_layout.py+ python tests/studio/playwright_collapse_layout.py --arm radix-grid --fillers 5000+ python tests/studio/playwright_collapse_layout.py --json > collapse-layout.json++It starts and stops its own vite dev server. Point it at one you already have with+SMOKE_BASE_URL, or move the port it picks with SMOKE_PORT.+"""++from __future__ import annotations++import argparse+import json+import os+import re+import sys+import time+from pathlib import Path++from playwright.sync_api import TimeoutError as PlaywrightTimeoutError+from playwright.sync_api import sync_playwright++sys.path.insert(0, str(Path(__file__).resolve().parent))+from _playwright_robust import ( # noqa: E402+ FRONTEND,+ chromium_launch_args,+ start_vite,+ stop_process,+ wait_for_smoke_page,+)++PORT = int(os.environ.get("SMOKE_PORT", "5217"))+# Unset: start and stop our own server. Set: drive that one and leave it running.+# Exported-but-empty counts as unset, else we skip the server and drive "" as the URL.+_EXTERNAL = os.environ.get("SMOKE_BASE_URL", "").strip()+BASE = _EXTERNAL or f"http://127.0.0.1:{PORT}"+OWNS_SERVER = not _EXTERNAL+# Under logs/ like every sibling harness; logs/ is gitignored, so the tree stays clean.+OUT = Path(os.environ.get("PW_ART_DIR", "logs/playwright-collapse-layout"))+LABEL = "collapse-layout"+SMOKE_PAGE = "smoke-collapse-layout.html"+SMOKE_ENTRY = "smoke-collapse-layout-main.tsx"++ARMS = ("radix-height", "radix-grid", "unmeasured-grid", "reasoning")++# The flag the `reasoning` arm follows is a build-time constant, so the page cannot report it.+# Read it out of the source vite is serving instead, and record it beside the numbers: a+# before/after table with no note of which side of the flag it came from is unreadable a week later.+FLAG_SOURCE = FRONTEND / "src" / "components" / "assistant-ui" / "thread-feature-flags.ts"++# Two document sizes, because the claim is about SCALING and a single size cannot show it. The+# small one is a plausible thread; the large one is where O(total layout objects) stops being a+# rounding error. One filler row is a block of a dozen inline boxes, so the layout-object count is+# roughly forty times the row count, and the report prints the element count the page measured+# rather than trusting this parameter.+DEFAULT_FILLERS = (200, 5000)+DEFAULT_PANE_PARAGRAPHS = int(os.environ.get("SMOKE_COLLAPSE_PANE_PARAGRAPHS", "40"))+DEFAULT_CYCLES = int(os.environ.get("SMOKE_COLLAPSE_CYCLES", "6"))+# Unthrottled by default: unlike a streaming render, a forced full-document layout is expensive on+# any machine, so there is nothing here that needs slowing down to become visible. Kept as a knob+# because throttling scales both sides of the comparison equally and can lift the signal on a box+# whose layout is fast enough that the small-filler column reads as noise.+DEFAULT_THROTTLE = int(os.environ.get("SMOKE_COLLAPSE_THROTTLE", "1"))++# The pane animates for 200ms. Everything below waits past that, so a measurement never lands+# while the transition is still running and the arms are never compared at different points of it.+SETTLE_MS = 400+# Deliberately INSIDE the 200ms, for the mid-flight growth check below.+MIDFLIGHT_GROW_DELAY_MS = 60+GROW_PARAGRAPHS = 20+# Enough of a forced-layout stack to reach the frame that names the effect it ran from.+STACK_FRAMES_KEPT = 4+# A five-thousand-row page is a real render in a dev server on a cold module graph.+READY_TIMEOUT_MS = 180_000++# `Layout` is emitted under `devtools.timeline`; the disabled-by-default siblings are where the+# invalidation stack lives and are cheap to ask for. The parse below matches on the event NAME and+# records whatever category it arrived under, so an upstream recategorisation shows up in the+# report as a changed category rather than as a silent zero.+TRACE_CATEGORIES = (+ "devtools.timeline",+ "disabled-by-default-devtools.timeline",+ "disabled-by-default-devtools.timeline.stack",+ "blink.user_timing",+)++# Clicking through Playwright would put its own hit-testing, and the layout reads that come with+# it, inside the trace window. The whole cycle also runs in one evaluate so a round trip cannot+# land between the open and the close of a single toggle.+TOGGLE_CYCLES_JS = """+async ([cycles, settleMs]) => {+ const trigger = () => document.querySelector('[data-probe="trigger"]');+ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));+ let clicks = 0;+ for (let i = 0; i < cycles; i += 1) {+ trigger().click();+ clicks += 1;+ await wait(settleMs);+ trigger().click();+ clicks += 1;+ await wait(settleMs);+ }+ return { clicks, state: trigger().getAttribute("data-state") };+}+"""++CLICK_TRIGGER_JS = """+() => {+ const trigger = document.querySelector('[data-probe="trigger"]');+ if (!trigger) {+ throw new Error('no [data-probe="trigger"] on the page');+ }+ trigger.click();+}+"""++# The arm mounted, and the hooks App installs in its effect are there to drive it. Checked+# separately from `__probeReady`, which is published from module scope and is therefore set even+# when the arm threw during render.+ARM_DRIVABLE_JS = """+() => Boolean(document.querySelector('[data-probe="trigger"]'))+ && typeof window.__probeGrow === "function"+ && typeof window.__probeReset === "function"+"""++# `overflowPx` is the whole streaming question in one number: how far the last paragraph's bottom+# sits below the pane's own box. A height animated to a value captured at toggle time clips+# whatever arrived afterwards; `1fr` re-resolves against the content every frame and cannot.+PANE_SNAPSHOT_JS = """+() => {+ const content = document.querySelector('[data-probe="content"]');+ if (!content) {+ return null;+ }+ const rect = content.getBoundingClientRect();+ const paragraphs = content.querySelectorAll("p");+ const last = paragraphs[paragraphs.length - 1];+ const round1 = (value) => Math.round(value * 10) / 10;+ return {+ height: round1(rect.height),+ paragraphs: paragraphs.length,+ overflowPx: last ? round1(last.getBoundingClientRect().bottom - rect.bottom) : null,+ state: content.getAttribute("data-state"),+ contentClass: String(content.className || ""),+ };+}+"""++_LOG = sys.stdout+++def info(message: str) -> None:+ print(f"[{LABEL}] {message}", file = _LOG, flush = True)+++def reasoning_flag_in_source() -> bool | None:+ """GRID_COLLAPSE_REASONING_ENABLED as written in the checkout this harness serves.++ None when the file cannot be read, which is the honest answer under SMOKE_BASE_URL: the+ server is then someone else's tree and this one says nothing about it.+ """+ # SMOKE_BASE_URL serves a bundle built somewhere else, so the local working tree is not+ # evidence about it. Reading it anyway would label a flag-on bundle as flag-off in the+ # report, which is the one thing the `reasoning` arm exists to get right.+ if _EXTERNAL:+ return None+ try:+ text = FLAG_SOURCE.read_text(encoding = "utf-8")+ except OSError:+ return None+ found = re.search(r"GRID_COLLAPSE_REASONING_ENABLED\s*=\s*(true|false)", text)+ return None if found is None else found.group(1) == "true"+++def metrics(cdp) -> dict[str, float]:+ got = cdp.send("Performance.getMetrics")+ return {m["name"]: m["value"] for m in got["metrics"]}+++def delta(before: dict[str, float], after: dict[str, float], name: str) -> float:+ return round(after.get(name, 0.0) - before.get(name, 0.0), 4)+++def start_tracing(cdp) -> list[dict]:+ """Begin a trace and return the list the `dataCollected` batches will land in.++ ReportEvents mode delivers nothing until `Tracing.end`, so the list stays empty until+ `stop_tracing` has pumped the events through.+ """+ collected: list[dict] = []+ cdp.on("Tracing.dataCollected", lambda payload: collected.extend(payload.get("value") or []))+ cdp.send(+ "Tracing.start",+ {+ "transferMode": "ReportEvents",+ "traceConfig": {+ "recordMode": "recordAsMuchAsPossible",+ "includedCategories": list(TRACE_CATEGORIES),+ },+ },+ )+ return collected+++def stop_tracing(+ cdp,+ page,+ collected: list[dict],+ *,+ timeout_s: float = 60.0,+) -> list[dict]:+ """End the trace and block until Chromium says it has handed over every batch.++ Reading `collected` straight after `Tracing.end` returns whatever happened to have arrived,+ which on a large trace is a truncated one, and a truncated trace is indistinguishable from a+ cheap toggle. The wait is a `wait_for_timeout` rather than a `sleep` because the sync API only+ dispatches CDP events while it is inside a call into the driver.+ """+ done = {"seen": False}+ cdp.on("Tracing.tracingComplete", lambda _payload: done.__setitem__("seen", True))+ cdp.send("Tracing.end")+ deadline = time.monotonic() + timeout_s+ while not done["seen"] and time.monotonic() < deadline:+ page.wait_for_timeout(50)+ if not done["seen"]:+ raise RuntimeError(f"the trace never completed within {timeout_s}s")+ return collected+++def _frame_label(frame: dict) -> str:+ """`functionName file.js:line`, with the dev server's URL and cache-busting query dropped.++ The full URL is three quarters host and `?v=` hash, which pushes the part that identifies the+ code off the end of any line the table prints.+ """+ url = str(frame.get("url") or "?").split("?")[0].rsplit("/", 1)[-1]+ return f"{frame.get('functionName') or '(anonymous)'} {url}:{frame.get('lineNumber', '?')}"+++def summarise_layouts(events: list[dict]) -> dict:+ """Fold the `Layout` events into the numbers this probe is about.++ `totalObjects` is the size of the tree under the relayout root and `dirtyObjects` the count+ that actually needed it, so their ratio is the statement being tested. `partialLayout` is+ Blink's own verdict on scope: false means it laid out the whole document.++ A `stackTrace` in `beginData` is present only when script forced the layout, which is why it+ is split out here: the unqualified count is mostly animation frames and does not separate the+ arms. It needs `disabled-by-default-devtools.timeline.stack` to be recorded, so a run whose+ forced column is zero everywhere is a run whose categories did not arrive, not a tree that+ stopped measuring.+ """+ durations: list[float] = []+ forced_durations: list[float] = []+ dirty: list[int] = []+ total: list[int] = []+ forced_total: list[int] = []+ whole_document = 0+ partial = 0+ unknown_scope = 0+ without_duration = 0+ categories: set[str] = set()+ sources: set[str] = set()+ for event in events:+ if event.get("name") != "Layout":+ continue+ categories.add(str(event.get("cat", "")))+ begin = (event.get("args") or {}).get("beginData") or {}+ stack = begin.get("stackTrace") or []+ # Complete ("X") events carry `dur`. A B/E pair does not, and counting one as a zero would+ # report a free toggle, so those are counted separately instead of averaged in.+ if event.get("dur") is None:+ without_duration += 1+ else:+ durations.append(event["dur"] / 1000.0)+ if stack:+ forced_durations.append(event["dur"] / 1000.0)+ if isinstance(begin.get("dirtyObjects"), int):+ dirty.append(begin["dirtyObjects"])+ if isinstance(begin.get("totalObjects"), int):+ total.append(begin["totalObjects"])+ if stack:+ forced_total.append(begin["totalObjects"])+ # Several frames, not one. The top of a forced-layout stack is an anonymous callee inside+ # the bundled dependency, which names the file but not the reason; the frame that says+ # this ran from a layout effect is a few down. Together they make a row attributable+ # instead of arguable.+ if stack:+ sources.add(" <- ".join(_frame_label(frame) for frame in stack[:STACK_FRAMES_KEPT]))+ scope = begin.get("partialLayout")+ if scope is True:+ partial += 1+ elif scope is False:+ whole_document += 1+ else:+ unknown_scope += 1+ return {+ "layouts": len(durations) + without_duration,+ "layout_ms": round(sum(durations), 2),+ "max_layout_ms": round(max(durations, default = 0.0), 2),+ "forced_layouts": len(forced_durations),+ "forced_layout_ms": round(sum(forced_durations), 2),+ "max_forced_layout_ms": round(max(forced_durations, default = 0.0), 2),+ "max_forced_total_objects": max(forced_total, default = 0),+ "forced_layout_sources": sorted(sources)[:5],+ "max_dirty_objects": max(dirty, default = 0),+ "max_total_objects": max(total, default = 0),+ "whole_document_layouts": whole_document,+ "partial_layouts": partial,+ "unknown_scope_layouts": unknown_scope,+ "events_without_duration": without_duration,+ "categories": sorted(c for c in categories if c),+ }+++def grow_probe(page) -> dict:+ """Grow the content of an OPEN pane and report whether the rendered height followed it.++ Two growths, because they fail differently. The settled one is the easy case. The mid-flight+ one starts while the open animation is still running, which is where a height captured at+ toggle time is already stale by the time it is applied, and is the shape of reasoning text+ streaming into a pane the reader has just opened.+ """+ # The toggle loop ran whole cycles, so the pane is closed and this click opens it.+ page.evaluate(CLICK_TRIGGER_JS)+ page.wait_for_timeout(SETTLE_MS)+ settled_before = page.evaluate(PANE_SNAPSHOT_JS)+ page.evaluate("(n) => window.__probeGrow(n)", GROW_PARAGRAPHS)+ page.wait_for_timeout(SETTLE_MS)+ settled_after = page.evaluate(PANE_SNAPSHOT_JS)++ # Back to a closed pane at the original size, so the mid-flight run opens from the state the+ # settled one did rather than from a pane that is already half as long again.+ page.evaluate("() => window.__probeReset()")+ page.wait_for_timeout(SETTLE_MS)+ page.evaluate(CLICK_TRIGGER_JS)+ page.wait_for_timeout(SETTLE_MS)++ page.evaluate(CLICK_TRIGGER_JS)+ page.wait_for_timeout(MIDFLIGHT_GROW_DELAY_MS)+ page.evaluate("(n) => window.__probeGrow(n)", GROW_PARAGRAPHS)+ # Twice the settle, because this growth lands during the transition and the row has to finish+ # resolving against content that changed underneath it.+ page.wait_for_timeout(SETTLE_MS * 2)+ midflight_after = page.evaluate(PANE_SNAPSHOT_JS)+ return {+ "settled_before": settled_before,+ "settled_after": settled_after,+ "midflight_after": midflight_after,+ "grow_paragraphs": GROW_PARAGRAPHS,+ "midflight_delay_ms": MIDFLIGHT_GROW_DELAY_MS,+ }+++def run_cell(context, arm: str, fillers: int, options: argparse.Namespace) -> dict:+ """One arm at one document size, on a page of its own.++ A fresh page per cell rather than a re-navigation: the layout tree, the style engine's caches+ and the metrics counters all start clean, and `Performance.getMetrics` is cumulative per page,+ so a shared page would make every cell after the first a delta against a warmed engine.+ """+ url = (+ f"{BASE}/{SMOKE_PAGE}?arm={arm}&fillers={fillers}"+ f"&paneParagraphs={options.pane_paragraphs}"+ )+ page = context.new_page()+ errors: list[str] = []+ page.on("pageerror", lambda e: errors.append(str(e)))+ problems: list[str] = []+ try:+ page.goto(url, wait_until = "domcontentloaded", timeout = READY_TIMEOUT_MS)+ # The page publishes `__probeReady` after two frames and puts the element count in it, so+ # "document size" in the report is measured rather than being the parameter restated.+ page.wait_for_function("() => Boolean(window.__probeReady)", timeout = READY_TIMEOUT_MS)+ ready = page.evaluate("() => window.__probeReady")++ try:+ page.wait_for_function(ARM_DRIVABLE_JS, timeout = 60_000)+ except PlaywrightTimeoutError as exc:+ raise RuntimeError(+ f"arm {arm!r} never rendered a [data-probe=trigger] with the grow hooks "+ f"installed; page errors so far: {errors}"+ ) from exc++ # Re-read the size AFTER the arm is drivable, and do not trust the value captured above.+ # Document size is the x axis of this experiment, so it is worth taking at the moment the+ # measurement actually starts rather than at the earliest moment the page was willing to+ # say anything. The page now publishes from a post-commit effect, but this harness also+ # runs against SMOKE_BASE_URL, where the served bundle may be an older one that still+ # published from module scope after two frames.+ ready["elements"] = page.evaluate("() => document.getElementsByTagName('*').length")++ # The page echoes the query it parsed. A renamed or misspelt parameter would otherwise+ # sweep four identical cells and report the flat line as a result.+ if ready.get("arm") != arm:+ problems.append(f"asked for arm {arm!r}, page reports {ready.get('arm')!r}")+ if ready.get("fillers") != fillers:+ problems.append(f"asked for {fillers} fillers, page reports {ready.get('fillers')!r}")+ if ready.get("paneParagraphs") != options.pane_paragraphs:+ problems.append(+ f"asked for {options.pane_paragraphs} pane paragraphs, page reports "+ f"{ready.get('paneParagraphs')!r}"+ )++ cdp = context.new_cdp_session(page)+ cdp.send("Performance.enable")+ # After load, so the page's own build is never throttled in, and recorded in the report so+ # a difference between cells can never be an artefact of uneven throttling.+ if options.throttle > 1:+ cdp.send("Emulation.setCPUThrottlingRate", {"rate": options.throttle})++ # One discarded cycle. The first open mounts the pane's content and resolves its styles+ # for the first time, which is real work that has nothing to do with the toggle and would+ # otherwise dominate the first measured cycle.+ page.evaluate(TOGGLE_CYCLES_JS, [1, SETTLE_MS])++ collected = start_tracing(cdp)+ before = metrics(cdp)+ toggled = page.evaluate(TOGGLE_CYCLES_JS, [options.cycles, SETTLE_MS])+ after = metrics(cdp)+ events = stop_tracing(cdp, page, collected)++ grown = grow_probe(page)+ finally:+ page.close()++ trace = summarise_layouts(events)+ return {+ "arm": arm,+ "fillers": fillers,+ "elements": ready.get("elements"),+ "cycles": options.cycles,+ "clicks": toggled["clicks"],+ "state_after_toggles": toggled["state"],+ "trace": trace,+ "cdp": {+ "layout_count": delta(before, after, "LayoutCount"),+ "layout_ms": round(delta(before, after, "LayoutDuration") * 1000, 2),+ "recalc_style_count": delta(before, after, "RecalcStyleCount"),+ "recalc_style_ms": round(delta(before, after, "RecalcStyleDuration") * 1000, 2),+ "task_ms": round(delta(before, after, "TaskDuration") * 1000, 2),+ },+ "grow": grown,+ "page_errors": errors,+ "problems": problems,+ }+++def render_table(cells: list[dict]) -> str:+ header = (+ f"{'arm':<16}{'fillers':>8}{'elements':>10}{'dirty':>7}{'total objs':>12}"+ f"{'forced':>8}{'forced ms':>11}{'max forced ms':>15}"+ f"{'layouts':>9}{'all ms':>9}{'cdp n':>8}{'cdp ms':>9}"+ )+ lines = [header, "-" * len(header)]+ for cell in cells:+ trace = cell["trace"]+ lines.append(+ f"{cell['arm']:<16}{cell['fillers']:>8,}{(cell['elements'] or 0):>10,}"+ f"{trace['max_dirty_objects']:>7,}{trace['max_total_objects']:>12,}"+ f"{trace['forced_layouts']:>8,}{trace['forced_layout_ms']:>11.2f}"+ f"{trace['max_forced_layout_ms']:>15.2f}"+ f"{trace['layouts']:>9,}{trace['layout_ms']:>9.2f}"+ f"{cell['cdp']['layout_count']:>8,.0f}{cell['cdp']['layout_ms']:>9.2f}"+ )+ return "\n".join(lines)+++def render_scaling(cells: list[dict]) -> str:+ """Small versus large, per arm. This is the comparison the whole page exists to make.++ Read against the forced layouts, since that is the column the arms differ on; the totals are+ dominated by whatever the arm animates.+ """+ by_arm: dict[str, list[dict]] = {}+ for cell in cells:+ by_arm.setdefault(cell["arm"], []).append(cell)+ lines: list[str] = []+ for arm, group in by_arm.items():+ if len(group) < 2:+ continue+ ordered = sorted(group, key = lambda c: c["fillers"])+ small, large = ordered[0], ordered[-1]++ def ratio(a: float, b: float) -> str:+ return f"{(b / a):.1f}x" if a > 0 else "n/a"++ small_forced = small["trace"]["max_forced_layout_ms"]+ large_forced = large["trace"]["max_forced_layout_ms"]+ lines.append(+ f"{arm:<16}{small['fillers']:,} -> {large['fillers']:,} fillers: "+ f"forced layouts {small['trace']['forced_layouts']} -> "+ f"{large['trace']['forced_layouts']}, "+ f"worst forced {small_forced:.2f}ms -> {large_forced:.2f}ms "+ f"({ratio(small_forced, large_forced)}), "+ f"total objects {small['trace']['max_total_objects']:,} -> "+ f"{large['trace']['max_total_objects']:,}, "+ f"whole-document layouts {small['trace']['whole_document_layouts']} -> "+ f"{large['trace']['whole_document_layouts']}"+ )+ return "\n".join(lines)+++def render_forced_sources(cells: list[dict]) -> str:+ """Where the forced layouts came from, so a surprising row can be attributed rather than+ argued about. On the Radix arms this is the collapsible's layout effect."""+ seen: dict[str, set[str]] = {}+ for cell in cells:+ for source in cell["trace"]["forced_layout_sources"]:+ seen.setdefault(cell["arm"], set()).add(source)+ return "\n".join(f"{arm:<16}{source}" for arm in sorted(seen) for source in sorted(seen[arm]))+++def render_growth(cells: list[dict]) -> str:+ header = (+ f"{'arm':<16}{'fillers':>8}{'settled px over':>17}{'midflight px over':>19}"+ f"{'paragraphs':>12}"+ )+ lines = [header, "-" * len(header)]+ for cell in cells:+ grown = cell["grow"]+ settled = grown.get("settled_after") or {}+ midflight = grown.get("midflight_after") or {}+ lines.append(+ f"{cell['arm']:<16}{cell['fillers']:>8,}"+ f"{_px(settled.get('overflowPx')):>17}{_px(midflight.get('overflowPx')):>19}"+ f"{str(settled.get('paragraphs')):>12}"+ )+ return "\n".join(lines)+++def _px(value) -> str:+ return "n/a" if value is None else f"{value:.1f}"+++def collect_failures(report: dict) -> list[str]:+ """Harness failures only.++ Nothing here reads a duration. A probe that failed when a toggle got slower would be red on+ the tree it is meant to describe, and the first fix for that is always to raise the number.+ What it does refuse is a run that measured nothing, because those are the ones that look like+ a clean result.+ """+ failures: list[str] = []+ cells = report["cells"]+ if not cells:+ failures.append("no cells ran")+ for cell in cells:+ where = f"{cell['arm']}@{cell['fillers']}"+ failures.extend(f"{where}: {problem}" for problem in cell["problems"])+ if cell["page_errors"]:+ failures.append(f"{where}: page errors: {cell['page_errors']}")+ if cell["clicks"] != cell["cycles"] * 2:+ failures.append(+ f"{where}: {cell['clicks']} clicks for {cell['cycles']} cycles; the toggle loop "+ "did not run"+ )+ if cell["trace"]["layouts"] <= 0:+ failures.append(+ f"{where}: the trace captured no Layout events, so every layout number in this "+ f"row is a zero that means 'not measured'. Categories seen: "+ f"{cell['trace']['categories']}"+ )+ if cell["cdp"]["layout_count"] <= 0:+ failures.append(+ f"{where}: Performance.getMetrics saw no layouts across {cell['cycles']} toggle "+ "cycles, so the pane never actually opened"+ )+ grown = cell["grow"]+ settled_before = grown.get("settled_before") or {}+ settled_after = grown.get("settled_after") or {}+ if not settled_before or not settled_after:+ failures.append(f"{where}: the pane was not open for the growth probe")+ elif settled_after.get("paragraphs", 0) <= settled_before.get("paragraphs", 0):+ failures.append(+ f"{where}: __probeGrow added no paragraphs "+ f"({settled_before.get('paragraphs')} -> {settled_after.get('paragraphs')}), so "+ "the streaming check measured nothing"+ )++ # The forced column is the one the arms are read on, and it is the one that goes quietly to+ # zero: it needs the disabled-by-default stack category, and a trace without it reports every+ # arm as forcing nothing, which looks like the fix already landed everywhere. radix-height is+ # the anchor, because Radix's measurement is unconditional upstream and cannot legitimately+ # read zero, so this is only asserted on a sweep that includes it.+ ran_radix_height = [cell for cell in cells if cell["arm"] == "radix-height"]+ if ran_radix_height and not any(cell["trace"]["forced_layouts"] for cell in cells):+ failures.append(+ "no arm recorded a script-forced layout, including radix-height, whose measurement is "+ "unconditional upstream. The Layout events arrived without `beginData.stackTrace`, so "+ "the forced columns are zeros that mean 'not measured'. Categories seen: "+ f"{sorted({c for cell in cells for c in cell['trace']['categories']})}"+ )++ # A sweep whose cells all rendered the same document proves nothing about scaling, and the+ # flat table it produces reads like a result rather than like a broken parameter.+ by_arm: dict[str, list[dict]] = {}+ for cell in cells:+ by_arm.setdefault(cell["arm"], []).append(cell)+ for arm, group in by_arm.items():+ if len(group) < 2:+ continue+ ordered = sorted(group, key = lambda c: c["fillers"])+ counts = [cell["elements"] or 0 for cell in ordered]+ if counts != sorted(counts) or counts[0] == counts[-1]:+ failures.append(+ f"{arm}: element counts {counts} do not grow with the filler sizes "+ f"{[cell['fillers'] for cell in ordered]}; the sweep compared identical documents"+ )+ return failures+++def parse_args(argv: list[str]) -> argparse.Namespace:+ parser = argparse.ArgumentParser(+ description = "Measure what a collapsible toggle costs against the whole document.",+ )+ parser.add_argument(+ "--arm",+ action = "append",+ choices = ARMS,+ help = "restrict the sweep to this arm; repeatable. Default: all four.",+ )+ parser.add_argument(+ "--fillers",+ default = None,+ help = (+ "comma separated filler-row counts to sweep. Default: "+ f"{','.join(str(n) for n in DEFAULT_FILLERS)}. A single value turns the sweep into "+ "one run and gives up the scaling comparison, which is the point of the sweep."+ ),+ )+ parser.add_argument(+ "--cycles",+ type = int,+ default = DEFAULT_CYCLES,+ help = f"open/close cycles per cell (default {DEFAULT_CYCLES}).",+ )+ parser.add_argument(+ "--pane-paragraphs",+ type = int,+ default = DEFAULT_PANE_PARAGRAPHS,+ help = (+ "paragraphs inside the pane. Identical across cells on purpose: it is what makes a "+ f"cost that grows with the filler attributable to the filler (default "+ f"{DEFAULT_PANE_PARAGRAPHS})."+ ),+ )+ parser.add_argument(+ "--throttle",+ type = int,+ default = DEFAULT_THROTTLE,+ help = f"CDP CPU throttling rate, 1 for off (default {DEFAULT_THROTTLE}).",+ )+ parser.add_argument(+ "--json",+ action = "store_true",+ help = "write the report to stdout as JSON; progress and tables move to stderr.",+ )+ parser.add_argument(+ "--headful",+ action = "store_true",+ help = "run the browser with a window, for watching a toggle by eye.",+ )+ args = parser.parse_args(argv)+ if args.fillers is None:+ args.filler_sizes = list(DEFAULT_FILLERS)+ else:+ try:+ args.filler_sizes = [int(part) for part in args.fillers.split(",") if part.strip()]+ except ValueError:+ parser.error(f"--fillers takes comma separated integers, got {args.fillers!r}")+ if not args.filler_sizes:+ parser.error("--fillers was empty")+ args.arms = list(args.arm) if args.arm else list(ARMS)+ if args.cycles < 1:+ parser.error("--cycles must be at least 1")+ return args+++def run(options: argparse.Namespace) -> dict:+ report: dict = {+ "label": LABEL,+ "base": BASE,+ "arms": options.arms,+ "filler_sizes": options.filler_sizes,+ "cycles": options.cycles,+ "pane_paragraphs": options.pane_paragraphs,+ "cpu_throttle": options.throttle,+ "grid_collapse_reasoning_enabled": reasoning_flag_in_source(),+ "cells": [],+ }+ with sync_playwright() as p:+ browser = p.chromium.launch(headless = not options.headful, args = chromium_launch_args())+ # A fixed viewport, because a filler row's height depends on how many times it wraps and+ # therefore on the width; a default that varied by machine would move the layout-object+ # count between runs of the same command.+ context = browser.new_context(viewport = {"width": 1200, "height": 900})+ try:+ for arm in options.arms:+ for fillers in options.filler_sizes:+ info(f"{arm} @ {fillers:,} fillers")+ report["cells"].append(run_cell(context, arm, fillers, options))+ finally:+ context.close()+ browser.close()+ return report+++def main(argv: list[str] | None = None) -> int:+ global _LOG+ options = parse_args(sys.argv[1:] if argv is None else argv)+ # Everything human goes to stderr under --json, so stdout stays a single parseable document.+ if options.json:+ _LOG = sys.stderr++ vite = None+ if OWNS_SERVER:+ info(f"starting vite dev server on port {PORT}")+ vite = start_vite(PORT)+ try:+ wait_for_smoke_page(+ f"{BASE}/{SMOKE_PAGE}",+ SMOKE_ENTRY,+ proc = vite,+ info = info,+ )+ report = run(options)+ finally:+ if vite is not None:+ stop_process(vite)+ info("vite stopped")++ report["harness_failures"] = collect_failures(report)++ out = OUT / f"{LABEL}.json"+ out.parent.mkdir(parents = True, exist_ok = True)+ out.write_text(json.dumps(report, indent = 2), encoding = "utf-8")++ flag = report["grid_collapse_reasoning_enabled"]+ info(f"GRID_COLLAPSE_REASONING_ENABLED in this checkout: {flag}")+ info(f"CPU throttle: {options.throttle}x, {options.cycles} open/close cycles per cell")+ info(+ "layout cost per cell (forced = laid out synchronously because script read a geometry; "+ "the rest is animation frames):\n" + render_table(report["cells"])+ )+ scaling = render_scaling(report["cells"])+ if scaling:+ info("scaling across document sizes:\n" + scaling)+ sources = render_forced_sources(report["cells"])+ if sources:+ info("what forced those layouts:\n" + sources)+ info(+ "growth into an open pane, as pixels of the last paragraph left below the pane's box "+ "(<= 0 means the rendered height followed the content; a small negative number is the "+ "last paragraph's own bottom margin):\n" + render_growth(report["cells"])+ )+ info(f"wrote {out}")++ if options.json:+ print(json.dumps(report, indent = 2), flush = True)++ if report["harness_failures"]:+ for failure in report["harness_failures"]:+ info(f"FAIL: {failure}")+ return 1+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/studio/test_chat_response_details_ui_contract.py b/tests/studio/test_chat_response_details_ui_contract.pyindex db397265a3c..7fa31075e18 100644--- a/tests/studio/test_chat_response_details_ui_contract.py+++ b/tests/studio/test_chat_response_details_ui_contract.py@@ -126,7 +126,16 @@ def test_reasoning_keeps_streaming_height_cap_through_automatic_collapse():assert "const [retainStreamingHeight, setRetainStreamingHeight]" in srcassert "setRetainStreamingHeight(false)" in srcassert "setRetainStreamingHeight(isReasoningStreaming)" in src- assert "isReasoningStreaming ? 0 : ANIMATION_DURATION" in src+ # Still zero while streaming, and still the animation's length once it stops. The+ # length is now chosen by the collapse mechanism rather than written inline: the+ # height keyframes animate a height captured at toggle time, so releasing the cap+ # cannot change what they animate and ANIMATION_DURATION is right for them, while+ # `1fr` resolves against the live content every frame and has to outlast a+ # transition that only starts a render after this timer is armed.+ assert "isReasoningStreaming ? 0 : closeDelay" in src+ assert "const closeDelay = GRID_COLLAPSE_REASONING_ENABLED" in src+ assert "? ANIMATION_DURATION + CLOSE_FALLBACK_MARGIN_MS" in src+ assert ": ANIMATION_DURATION;" in srcassert "streaming={isReasoningStreaming || retainStreamingHeight}" in srcdiff --git a/tests/studio/test_playwright_suites_run_in_ci.py b/tests/studio/test_playwright_suites_run_in_ci.pyindex 4b607b97506..0b5093d99fe 100644--- a/tests/studio/test_playwright_suites_run_in_ci.py+++ b/tests/studio/test_playwright_suites_run_in_ci.py@@ -40,6 +40,16 @@ NOT_IN_CI = {# can go wrong silently, the verdict in harness_failures, is driven without a# browser by test_autoscroll_harness_contract.py, which CI does run."playwright_thread_weight.py",+ # The same shape as playwright_thread_weight.py: a measurement harness, not a+ # gate. It prints what a collapsible toggle costs against document size, and it+ # deliberately sets no budget, because the number is hardware-dependent and a+ # threshold here would be flaky rather than informative. The cells that make the+ # O(total layout objects) curve readable run 100k+ element documents and cost+ # minutes. Run by hand when that curve needs re-measuring. What it asserts that+ # CANNOT go stale silently, the flag wiring and the absence of a measurement in+ # the unmeasured primitive, is covered without a browser by+ # studio/frontend/tests/reasoning-grid-collapse.test.ts, which CI does run.+ "playwright_collapse_layout.py",}