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: keep the overlay rail honest about what it reserves (#10372)
Daniel Han7ba00bba87c4
diff --git a/studio/frontend/src/app/provider.tsx b/studio/frontend/src/app/provider.tsxindex 3e8f5a82e16..c653cbab7bd 100644--- a/studio/frontend/src/app/provider.tsx+++ b/studio/frontend/src/app/provider.tsx@@ -421,6 +421,11 @@ function TauriUpdateLayer({// cards still land on 16px, since the box sits on the floor and the// bottom gutter carries them back up.className="pointer-events-none fixed bottom-0 right-4 -mx-3 flex max-h-[calc(100dvh_-_8px)] flex-col items-end gap-2 overflow-y-auto overflow-x-hidden overscroll-contain px-3"+ // The rail is measured from the outside, per card, by+ // tests/studio/playwright_update_banner_layout.py. Reaching it through+ // whichever banner happens to be up finds nothing when none is, which is+ // exactly the state the download panel has to be judged in.+ data-testid="overlay-rail"// Block gutter in px, never a spacing utility: those are rem, and at any// root but 16px the cards would drift off the corner. Across stays a// utility, since px-3 and -mx-3 cancel whatever a rem is worth.@@ -737,6 +742,11 @@ function TauriWrapper({ children }: { children: ReactNode }) {// padding. The cards still land on 16px, since the box sits on the// floor and the bottom gutter carries them back up.className="pointer-events-none fixed bottom-0 right-4 -mx-3 flex max-h-[calc(100dvh_-_8px)] flex-col items-end gap-2 overflow-y-auto overflow-x-hidden overscroll-contain px-3"+ // The rail is measured from the outside, per card, by+ // tests/studio/playwright_update_banner_layout.py. Reaching it through+ // whichever banner happens to be up finds nothing when none is, which is+ // exactly the state the download panel has to be judged in.+ data-testid="overlay-rail"// Block gutter in px, never a spacing utility: those are rem, and at// any root but 16px the cards would drift off the corner.style={{diff --git a/studio/frontend/tests/download-panel-not-permanent.test.ts b/studio/frontend/tests/download-panel-not-permanent.test.tsnew file mode 100644index 00000000000..6d8ba0f7374--- /dev/null+++ b/studio/frontend/tests/download-panel-not-permanent.test.ts@@ -0,0 +1,238 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/**+ * The Downloads overlay must unmount when the job list is empty (#9849, which+ * shipped a permanent corner FAB and was reverted by #10298).+ *+ * The second consequence is the one that reads as harmless: the rail is a+ * `flex flex-col gap-2` column, so a panel returning a wrapper instead of+ * `null` takes a slot and its gap, pushing the loaded models card off the+ * corner it is meant to hold.+ *+ * Read from the source: the node suite has no DOM. Matched through the AST, so+ * reformatting or a rename of `jobKeys` cannot quietly retire it.+ */++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++import ts from "typescript";++import { openingTag } from "./helpers/tsx-ast.ts";++const parse = (relative: string, name: string): ts.SourceFile =>+ ts.createSourceFile(+ name,+ readFileSync(new URL(`../src/${relative}`, import.meta.url), "utf8"),+ ts.ScriptTarget.ESNext,+ true,+ ts.ScriptKind.TSX,+ );++const PANEL_PATH = "features/hub/download-manager/download-manager-panel.tsx";+const panel = parse(PANEL_PATH, "download-manager-panel.tsx");+const provider = parse("app/provider.tsx", "provider.tsx");++function panelComponent(): ts.FunctionDeclaration {+ let found: ts.FunctionDeclaration | null = null;+ const visit = (node: ts.Node): void => {+ if (+ ts.isFunctionDeclaration(node) &&+ node.name?.getText() === "DownloadManagerPanel"+ ) {+ found = node;+ }+ ts.forEachChild(node, visit);+ };+ ts.forEachChild(panel, visit);+ assert.ok(found, `${PANEL_PATH} no longer exports a DownloadManagerPanel`);+ return found;+}++/** The ordered-job-keys local, found by its initializer so a rename cannot slip past. */+function jobKeysBinding(component: ts.FunctionDeclaration): string {+ let name: string | null = null;+ const visit = (node: ts.Node): void => {+ if (+ ts.isVariableDeclaration(node) &&+ ts.isIdentifier(node.name) &&+ node.initializer &&+ ts.isCallExpression(node.initializer) &&+ node.initializer.expression.getText() === "useDownloadManagerStore" &&+ node.initializer.arguments.some((arg) =>+ /orderedJobKeys/i.test(arg.getText()),+ )+ ) {+ name = node.name.getText();+ }+ ts.forEachChild(node, visit);+ };+ ts.forEachChild(component, visit);+ assert.ok(+ name,+ `${PANEL_PATH}: no local is bound from useDownloadManagerStore with the+ordered-job-keys selector, so the guard below cannot be located. If the+selector was renamed, update this test; if the panel stopped reading the+job list at all, it can no longer know when to unmount.`,+ );+ return name;+}++/** Operand order matters: unordered also accepts `0 < jobKeys.length`, the inverse. */+function isEmptyTest(node: ts.Node, jobKeys: string): boolean {+ const length = `${jobKeys}.length`;+ const K = ts.SyntaxKind;+ // [left, operator, right], each meaning the list is empty.+ const shapes: [string, ts.SyntaxKind, string][] = [+ [length, K.EqualsEqualsEqualsToken, "0"],+ ["0", K.EqualsEqualsEqualsToken, length],+ [length, K.LessThanToken, "1"],+ [length, K.LessThanEqualsToken, "0"],+ ["0", K.GreaterThanEqualsToken, length],+ ["1", K.GreaterThanToken, length],+ ];+ if (ts.isBinaryExpression(node)) {+ const left = node.left.getText();+ const right = node.right.getText();+ const op = node.operatorToken.kind;+ return shapes.some(([l, o, r]) => left === l && op === o && right === r);+ }+ return (+ ts.isPrefixUnaryExpression(node) &&+ node.operator === K.ExclamationToken &&+ node.operand.getText() === length+ );+}++/**+ * Does an empty list force `condition` true? Finding the comparison somewhere+ * inside it is a different question, wrong in both directions: `... === 0 &&+ * activeCount > 0` covers some empty states, `!(... === 0)` none. Evaluated with+ * the empty test pinned true and every other term unknown.+ */+type Truth = true | false | null;++function underAnEmptyList(node: ts.Node, jobKeys: string): Truth {+ if (isEmptyTest(node, jobKeys)) return true;+ if (ts.isParenthesizedExpression(node)) {+ return underAnEmptyList(node.expression, jobKeys);+ }+ if (+ ts.isPrefixUnaryExpression(node) &&+ node.operator === ts.SyntaxKind.ExclamationToken+ ) {+ const inner = underAnEmptyList(node.operand, jobKeys);+ return inner === null ? null : !inner;+ }+ if (ts.isBinaryExpression(node)) {+ const op = node.operatorToken.kind;+ const left = underAnEmptyList(node.left, jobKeys);+ const right = underAnEmptyList(node.right, jobKeys);+ if (op === ts.SyntaxKind.BarBarToken) {+ if (left === true || right === true) return true;+ if (left === false && right === false) return false;+ return null;+ }+ if (op === ts.SyntaxKind.AmpersandAmpersandToken) {+ if (left === false || right === false) return false;+ if (left === true && right === true) return true;+ return null;+ }+ }+ return null; // Unknown, so it cannot carry the guard.+}++function returnsNull(statement: ts.Statement): boolean {+ const body = ts.isBlock(statement) ? statement.statements : [statement];+ return body.some(+ (node) =>+ ts.isReturnStatement(node) &&+ node.expression?.kind === ts.SyntaxKind.NullKeyword,+ );+}++test("the Downloads overlay unmounts when there are no jobs", () => {+ const component = panelComponent();+ const jobKeys = jobKeysBinding(component);+ const statements = component.body?.statements ?? ts.factory.createNodeArray();++ // Top level only: a nested guard still leaves mounted-and-empty states.+ const guarded = statements.some(+ (statement) =>+ ts.isIfStatement(statement) &&+ returnsNull(statement.thenStatement) &&+ underAnEmptyList(statement.expression, jobKeys) === true,+ );++ assert.ok(+ guarded,+ `${PANEL_PATH}: DownloadManagerPanel must return null while ${jobKeys} is+empty, at the top level of the component.++Without it the Downloads overlay is permanent: a bottom-right FAB on+every hub route of a fresh install, and a flex slot in the rail that+pushes the loaded models card off the corner even when it paints+nothing. That is PR #9849, which had to be reverted by PR #10298.++Expected something of the shape: if (... || ${jobKeys}.length === 0) return null;`,+ );+});++test("the rail-facing wrapper can still be squeezed by the rail's cap", () => {+ // min-h-0: without it a flex item floors at auto and the capped rail squeezes+ // the update card above instead of this list.+ const source = readFileSync(+ new URL(`../src/${PANEL_PATH}`, import.meta.url),+ "utf8",+ );+ const ternary = source.match(/positioned\s*\?\s*"([^"]*)"\s*:\s*"([^"]*)"/);+ assert.ok(+ ternary,+ `${PANEL_PATH}: the positioned/stacked className ternary is gone, so the+rail-facing branch can no longer be checked`,+ );+ assert.match(+ ternary[1],+ /\bfixed\b.*\bbottom-4\b.*\bright-4\b/,+ `${PANEL_PATH}: the standalone panel has left the bottom-right corner`,+ );+ assert.match(+ ternary[2],+ /\bmin-h-0\b/,+ `${PANEL_PATH}: the stacked branch dropped min-h-0, so a capped rail will+squeeze the update card above this list instead of the list`,+ );+});++test("the Downloads panel sits above the loaded models card in both rails", () => {+ // The loaded models card holds the corner; this one comes and goes above it.+ const tags: { name: string; at: number }[] = [];+ const visit = (node: ts.Node): void => {+ const opening = openingTag(node);+ const name = opening?.tagName.getText();+ if (name === "DownloadManagerPanel" || name === "LoadedModelsIndicator") {+ tags.push({ name, at: node.getStart() });+ }+ ts.forEachChild(node, visit);+ };+ ts.forEachChild(provider, visit);+ tags.sort((a, b) => a.at - b.at);++ const panels = tags.filter((t) => t.name === "DownloadManagerPanel");+ const indicators = tags.filter((t) => t.name === "LoadedModelsIndicator");+ assert.ok(+ panels.length > 0 && panels.length === indicators.length,+ `provider.tsx: expected the download panel and the loaded models card to be+paired in every rail, found ${panels.length} and ${indicators.length}`,+ );+ for (let i = 0; i < panels.length; i += 1) {+ assert.ok(+ panels[i].at < indicators[i].at,+ "provider.tsx: DownloadManagerPanel is rendered below LoadedModelsIndicator.\n" ++ "The rail is a bottom-anchored column, so the last child is the one on\n" ++ "the corner, and that is meant to be the loaded models card.",+ );+ }+});diff --git a/studio/frontend/tests/overlay-rail-floor-gating.test.ts b/studio/frontend/tests/overlay-rail-floor-gating.test.tsnew file mode 100644index 00000000000..fc93b20c198--- /dev/null+++ b/studio/frontend/tests/overlay-rail-floor-gating.test.ts@@ -0,0 +1,330 @@+// 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 card in the bottom-right rail may not reserve height it does not paint.+ *+ * The rail is bottom-anchored, so dead space inside a card lifts everything+ * visible off the corner. #10117 put an ungated floor on the llama.cpp banner+ * whose changelog only renders once opened: 204.2px reserved, 147.3px painted.+ * Fixed by #10229.+ *+ * The rule pinned here, rather than a spelling: a floor may only be reserved+ * when the thing it protects is on screen. Two gates satisfy it, the CSS+ * `has-[[data-slot=...]]:` and a React predicate that also renders the panel.+ * The suite that missed #10117 asserted the floor was PRESENT, so a spelling+ * check can be edited into agreement with the bug it should catch.+ *+ * Read from the source: the node suite has no DOM. The geometry itself is in+ * tests/studio/playwright_update_banner_layout.py.+ */++import assert from "node:assert/strict";+import { existsSync, readFileSync, readdirSync } from "node:fs";+import { join } from "node:path";+import test from "node:test";+import { fileURLToPath } from "node:url";++import ts from "typescript";++import { openingTag } from "./helpers/tsx-ast.ts";++const src = (relative: string): URL =>+ new URL(`../src/${relative}`, import.meta.url);++const parse = (path: URL, name: string): ts.SourceFile =>+ ts.createSourceFile(+ name,+ readFileSync(path, "utf8"),+ ts.ScriptTarget.ESNext,+ true,+ ts.ScriptKind.TSX,+ );++const provider = parse(src("app/provider.tsx"), "provider.tsx");++/** The rails, matched on the corner they are anchored to. */+const RAIL_ANCHOR = "pointer-events-none fixed bottom-0 right-4";++/**+ * Every component that ends up in a rail. Two sources: literal children of an+ * anchored rail miss whatever the Tauri layer takes through `{children}`, and+ * `positioned={false}` misses a card that takes no such prop.+ */+function railChildren(): string[] {+ const names = new Set<string>();+ const visit = (node: ts.Node): void => {+ if (ts.isJsxElement(node)) {+ const className = node.openingElement.attributes.properties.find(+ (p): p is ts.JsxAttribute =>+ ts.isJsxAttribute(p) && p.name.getText() === "className",+ );+ if (className?.getText().includes(RAIL_ANCHOR)) {+ for (const child of node.children) {+ const name = openingTag(child)?.tagName.getText();+ if (name && /^[A-Z]/.test(name)) names.add(name);+ }+ }+ }+ const tag = openingTag(node);+ if (tag && /^[A-Z]/.test(tag.tagName.getText())) {+ const stacked = tag.attributes.properties.some(+ (p) =>+ ts.isJsxAttribute(p) &&+ p.name.getText() === "positioned" &&+ p.initializer &&+ ts.isJsxExpression(p.initializer) &&+ p.initializer.expression?.kind === ts.SyntaxKind.FalseKeyword,+ );+ if (stacked) names.add(tag.tagName.getText());+ }+ ts.forEachChild(node, visit);+ };+ ts.forEachChild(provider, visit);+ return [...names].sort();+}++/** Where `name` is imported from, resolved on disk. Barrels followed one hop. */+function sourceOf(name: string): { path: URL; label: string } | null {+ let specifier: string | null = null;+ for (const statement of provider.statements) {+ if (!ts.isImportDeclaration(statement)) continue;+ const bindings = statement.importClause?.namedBindings;+ if (!bindings || !ts.isNamedImports(bindings)) continue;+ if (bindings.elements.some((el) => el.name.getText() === name)) {+ specifier = (statement.moduleSpecifier as ts.StringLiteral).text;+ }+ }+ if (!specifier?.startsWith("@/")) return null;++ const resolve = (relative: string): URL | null => {+ for (const candidate of [`${relative}.tsx`, `${relative}.ts`]) {+ const url = src(candidate);+ if (existsSync(fileURLToPath(url))) return url;+ }+ return null;+ };++ const base = specifier.slice(2);+ const direct = resolve(base);+ if (direct) return { path: direct, label: base };++ const index = resolve(`${base}/index`);+ if (!index) return null;+ const barrel = readFileSync(index, "utf8");+ const re = new RegExp(+ `export\\s*\\{[^}]*\\b${name}\\b[^}]*\\}\\s*from\\s*"\\./([^"]+)"`,+ );+ const hop = barrel.match(re);+ if (!hop) return null;+ const followed = resolve(`${base}/${hop[1]}`);+ return followed ? { path: followed, label: `${base}/${hop[1]}` } : null;+}++/**+ * Any spelling, since a rule that knows only `min-h-[calc(` is retired by+ * rewriting it. `min-h-0` removes the flex `auto` default, so it is not a floor.+ */+const FLOOR_TOKEN = /(^|:)min-h-(?!0$)\S+/;++/** getText() keeps the quotes, which are not class tokens. */+const classTokens = (literal: ts.Node): string[] =>+ literal.getText().replace(/["'`]/g, " ").split(/\s+/).filter(Boolean);++const isFloor = (token: string): boolean => FLOOR_TOKEN.test(token);++function floorLiterals(file: ts.SourceFile): ts.Node[] {+ const found: ts.Node[] = [];+ const visit = (node: ts.Node): void => {+ if (+ (ts.isStringLiteral(node) ||+ ts.isNoSubstitutionTemplateLiteral(node) ||+ ts.isTemplateExpression(node)) &&+ classTokens(node).some(isFloor)+ ) {+ found.push(node);+ }+ ts.forEachChild(node, visit);+ };+ ts.forEachChild(file, visit);+ return found;+}++/**+ * The protected panels and the slots they declare, read out of the tree, not+ * matched by name: a substring rule accepts a `<ChangelogToggle>` and a free+ * `data-slot` accepts `card-footer`, which an always-present footer makes+ * permanent. A panel is one rendering the shared notes layout root.+ */+function notesPanels(): { components: Set<string>; slots: Set<string> } {+ const components = new Set<string>();+ const slots = new Set<string>();+ const dir = fileURLToPath(src("components"));+ for (const entry of readdirSync(dir, {+ recursive: true,+ withFileTypes: true,+ })) {+ if (!entry.isFile() || !entry.name.endsWith(".tsx")) continue;+ const text = readFileSync(join(entry.parentPath, entry.name), "utf8");+ if (!text.includes("UPDATE_NOTES_ROOT_CLASS")) continue;+ for (const hit of text.matchAll(/export function ([A-Z]\w*)/g)) {+ components.add(hit[1]);+ }+ for (const hit of text.matchAll(/data-slot="([^"]+)"/g)) slots.add(hit[1]);+ }+ return { components, slots };+}++const NOTES = notesPanels();++/** Is every floor in `literal` gated by `:has()` on a slot the panel declares? */+function gatedByHas(literal: ts.Node): boolean {+ const tokens = classTokens(literal).filter(isFloor);+ return (+ tokens.length > 0 &&+ tokens.every((token) => {+ const slot = token.match(/has-\[\[data-slot=([^\]]+)\]\]:min-h-/);+ return slot !== null && NOTES.slots.has(slot[1]);+ })+ );+}++/**+ * `whenTrue` only. A floor in the other branch applies when its predicate is+ * false, which is no gate at all: `showFailure ? "shrink-0" : "<floor>"`, the+ * shape #8367 shipped, floors every state except the one named.+ */+function branchConditions(literal: ts.Node): string[] {+ const conditions: string[] = [];+ let node: ts.Node = literal;+ let parent = node.parent;+ while (parent && !ts.isJsxAttribute(parent)) {+ if (ts.isConditionalExpression(parent) && parent.whenTrue === node) {+ conditions.push(parent.condition.getText());+ }+ node = parent;+ parent = parent.parent;+ }+ return conditions;+}++/**+ * Rendering something is not enough: `changelogAvailable` renders the toggle and+ * is true while the panel is closed, which is #10117 exactly. It must render the+ * notes themselves.+ */+/** The className painted inside this floor's own slot: its element's first child. */+function paintedSurface(literal: ts.Node): string | null {+ let node: ts.Node | undefined = literal;+ while (node && !ts.isJsxAttribute(node)) node = node.parent;+ // attribute -> attributes -> opening tag+ const opening = node?.parent?.parent;+ if (!opening || !ts.isJsxOpeningElement(opening)) return null;+ const owner = opening.parent;+ if (!ts.isJsxElement(owner)) return null;+ for (const child of owner.children) {+ const tag = openingTag(child);+ if (!tag) continue;+ const className = tag.attributes.properties.find(+ (p): p is ts.JsxAttribute =>+ ts.isJsxAttribute(p) && p.name.getText() === "className",+ );+ return className?.initializer?.getText() ?? "";+ }+ return null;+}++function gatesTheNotes(source: string, condition: string): boolean {+ const name = condition.trim();+ if (!/^[A-Za-z_$][\w$]*$/.test(name)) return false;+ const rendered = new RegExp(+ `\\b${name}\\b[^;{}]{0,160}?(\\?|&&)\\s*\\(?\\s*<([A-Za-z][\\w.]*)`,+ "g",+ );+ for (const hit of source.matchAll(rendered)) {+ if (NOTES.components.has(hit[2])) return true;+ }+ return false;+}++const CHILDREN = railChildren();++test("the rail's children are all resolvable, or this file proves nothing", () => {+ assert.ok(+ CHILDREN.length >= 3,+ `provider.tsx: found ${CHILDREN.length} cards in a rail anchored on+"${RAIL_ANCHOR}". Either the rail moved or its children are no longer+rendered inline, and every check below just skipped silently.`,+ );+ for (const name of CHILDREN) {+ assert.ok(+ sourceOf(name),+ `provider.tsx: cannot follow <${name} /> to a source file, so its floor+cannot be checked. Add the import path it resolves through.`,+ );+ }+});++for (const name of CHILDREN) {+ test(`${name} reserves no height it may not paint`, () => {+ const resolved = sourceOf(name);+ assert.ok(resolved, `<${name} /> did not resolve`);+ const file = parse(resolved.path, `${name}.tsx`);+ const source = readFileSync(resolved.path, "utf8");+ // Invisible to the analysis below; the rail keeps its geometry in CSS.+ assert.doesNotMatch(+ source,+ /\bminHeight\s*:/,+ `${resolved.label}: a floor is set from JS. The rail's cards floor in CSS+so the gate can be read here and by the browser suite; an inline minHeight is+reserved unconditionally and nothing checks it.`,+ );++ const literals = floorLiterals(file);+ if (literals.length === 0) return; // No floor, nothing to gate.++ for (const literal of literals) {+ const gated =+ gatedByHas(literal) ||+ branchConditions(literal).some((condition) =>+ gatesTheNotes(source, condition),+ );+ assert.ok(+ gated,+ `${resolved.label}: a min-h floor is applied without being gated on the+panel it exists to protect, so the card reserves height it may paint none of.+In a bottom-anchored rail that dead space lifts every visible card off the+corner. This is PR #10117, fixed by PR #10229.++Gate it one of the two ways already in use:+ has-[[data-slot=update-release-notes]]:min-h-[...] (CSS)+ changelogPanelOpen ? "min-h-[...]" : "shrink-0" (React, using the same+ predicate that renders the notes or changelog panel)++A predicate that renders something else does not count: changelogAvailable+renders the changelog toggle and is true while the panel is still closed, which+is the state that reserved 64.9px in #10117.++Floor found in: ${literal.getText().slice(0, 200)}+Ternary conditions around it: ${branchConditions(literal).join(", ") || "(none)"}`,+ );++ // This floor's own painted child, not any `grow` in the file: an alternate+ // branch carrying one would answer for a surface that does not.+ const surface = paintedSurface(literal);+ assert.ok(+ surface,+ `${resolved.label}: cannot find the element painted inside the floored+slot, so nothing checks that the floor is filled.`,+ );+ assert.match(+ surface,+ /\bgrow\b/,+ `${resolved.label}: the floored slot's painted child has no \`grow\`, so+short content leaves an unpainted gap inside the height the floor reserved.++Painted child: ${surface.slice(0, 160)}`,+ );+ }+ });+}diff --git a/tests/studio/playwright_update_banner_layout.py b/tests/studio/playwright_update_banner_layout.pyindex 46be08ab346..b0ca5091441 100644--- a/tests/studio/playwright_update_banner_layout.py+++ b/tests/studio/playwright_update_banner_layout.py@@ -274,6 +274,10 @@ INDICATOR_VIEWPORTS = [(921, 534), (768, 500)]# One roomy viewport and one capped viewport.NO_PREVIEW_VIEWPORTS = [(1440, 900), (921, 534)]+# Where the cards sit, off both edges. The rail carries a shadow gutter, so this+# is the cards' inset and not the rail's own box; see RAIL_CORNER below.+CORNER_INSET_PX = 16+# Where the rail actually is, against the corner it is anchored to. It was placed from JS for a while, lifting clear# of the boxes in the frame store, and drifted to the middle and the top of the window as those boxes and its own# cards changed. Nothing on the page may move it now.@@ -284,9 +288,10 @@ RAIL_CORNER = """const rail = card.parentElement;const a = rail.getBoundingClientRect();// Cards in the rail's own flow. A dragged loaded models card is `fixed`- // somewhere else and says nothing about the rail.+ // somewhere else and says nothing about the rail; `relative` and `sticky`+ // still take part in layout, so only the out-of-flow pair is excluded.const flowed = Array.from(rail.children).filter(- (kid) => getComputedStyle(kid).position === 'static',+ (kid) => !['absolute', 'fixed'].includes(getComputedStyle(kid).position),);return {rail: {top: Math.round(a.top), bottom: Math.round(a.bottom),@@ -464,7 +469,18 @@ MEASURE = """const snooze = q('[data-testid="web-update-snooze-button"]');const copy = q('[data-testid="web-update-copy-button"]');const footer = snooze ? snooze.closest('div').parentElement : null;- const rail = card ? card.parentElement : (llama ? llama.parentElement : null);+ // By its own handle, not through whichever banner happens to be up: reaching+ // the rail via a card finds nothing when no card is up, and "no cards" is a+ // state the download panel and the loaded models card have to be judged in.+ const rail = document.querySelector('[data-testid="overlay-rail"]')+ || (card ? card.parentElement : (llama ? llama.parentElement : null));+ // Cards in the rail's own flow. A dragged loaded models card is `fixed`+ // somewhere else and says nothing about the rail; `relative` and `sticky`+ // still take part in layout, so only the out-of-flow pair is excluded.+ const flowed = rail+ ? [...rail.children].filter(+ (kid) => !['absolute', 'fixed'].includes(getComputedStyle(kid).position))+ : [];// The clipper is the card's inner surface, the one with overflow-hidden; the// rail-facing root above it is overflow-visible and clips nothing.const surface = card ? card.firstElementChild : null;@@ -474,6 +490,30 @@ MEASURE = """// fold the reader can scroll to; what the card hides is gone for good.card: rect(card), llama: rect(llama),cardDead: dead(card), llamaDead: dead(llama),+ // Every card in the rail, not only the two update banners. #10117 put an+ // ungated floor on a card that had none the day before, so naming the cards+ // to check is naming the ones that have already gone wrong.+ railCards: flowed.map((kid) => ({+ // Enough to name the offender in the failure without opening a browser.+ tag: kid.tagName.toLowerCase(),+ testid: kid.getAttribute('data-testid'),+ cls: (kid.getAttribute('class') || '').slice(0, 120),+ painted: kid.firstElementChild+ ? (kid.firstElementChild.getAttribute('class') || '').slice(0, 80)+ : null,+ dead: dead(kid),+ })),+ // Where the bottom-most card ACTUALLY paints, against the corner it is+ // anchored to. `fromBottom` in RAIL_CORNER comes off the rail's padding+ // box, which is `fixed bottom-0` and so reports the intended offset however+ // much dead air sits inside the last card. That is why the rail passed its+ // own corner check all through #10117. This reads the painted surface.+ lastPaintedFromBottom: (() => {+ const last = flowed[flowed.length - 1];+ const paint = last && (last.firstElementChild || last);+ if (!paint) return null;+ return Math.round((innerHeight - paint.getBoundingClientRect().bottom) * 10) / 10;+ })(),// The same two, as much of them as the rail is SHOWING. Containment is// asked of these: a card the rail has folded away is not on screen at all,// and judging its unclipped rect against the viewport fails it for being@@ -673,15 +713,31 @@ def measure(page, label: str) -> dict:facts["gutterIsRail"] is False,f"scrolls={scrolls} gutterIsRail={facts['gutterIsRail']}",)- # A floor must not leave unpainted space around a compact card.- for name in ("card", "llama"):- hole = facts[f"{name}Dead"]+ # The rail is bottom-anchored, so one card's dead space lifts the rest off the corner.+ cards = facts["railCards"]+ check(+ f"{label}: the rail has cards to judge",+ len(cards) > 0,+ f"railCards={cards}, so every dead-space check below passed vacuously",+ )+ for index, kid in enumerate(cards):+ hole = kid["dead"]if hole is None:continue+ who = kid["testid"] or kid["cls"] or f"{kid['tag']}#{index}"check(- f"{label}: the {name}'s slot reserves no height it does not paint",+ f"{label}: {who} reserves no height it does not paint",hole["above"] <= 1.0 and hole["below"] <= 1.0,- f"{name}Dead={hole}",+ f"dead={hole} painted-child={kid['painted']}",+ )+ # Measured off the card the reader sees. Not while scrolling: under the cap the+ # bottom card is wherever the scroll position puts it, which REACH covers.+ if cards and not facts["railScrolls"]:+ check(+ f"{label}: the bottom card is on the corner, not floating above it",+ facts["lastPaintedFromBottom"] == CORNER_INSET_PX,+ f"lastPaintedFromBottom={facts['lastPaintedFromBottom']} "+ f"(want {CORNER_INSET_PX}) last={cards[-1]}",)# The notes are allowed to yield all of their height, and do; the controls are not, and a card clipped to nothing is# the failure being tested for.@@ -695,6 +751,49 @@ def measure(page, label: str) -> dict:return facts+# #9849 made the Downloads overlay always mount, and was reverted by #10298.+DOWNLOADS = """+() => {+ const rail = document.querySelector('[data-testid="overlay-rail"]');+ if (!rail) return null;+ return {+ // The panel and its collapsed FAB. Neither may exist with no jobs.+ panels: document.querySelectorAll('.hub-download-panel, .hub-download-fab').length,+ // Slots, not pixels: a panel that renders a wrapper around nothing is+ // invisible but still takes a flex slot and its gap-2, which pushes the+ // card that is meant to hold the corner up off it.+ cards: [...rail.children].filter(+ (kid) => !['absolute', 'fixed'].includes(getComputedStyle(kid).position)).length,+ };+}+"""+++def check_downloads_absent(page, label: str, expected_cards: int) -> None:+ """With no transfers, the Downloads overlay must not be in the rail at all."""+ seen = page.evaluate(DOWNLOADS)+ check(+ f"{label}: the rail is reachable by its own handle",+ seen is not None,+ "no [data-testid=overlay-rail] on the page, so the two checks below prove nothing",+ )+ if seen is None:+ return+ check(+ f"{label}: no Downloads overlay while there is nothing downloading",+ seen["panels"] == 0,+ f"{seen['panels']} download panel(s) mounted with an empty job list, "+ "which is the permanent corner FAB from #9849",+ )+ # An exact count: a bare absence also holds when the selector has rotted.+ check(+ f"{label}: the rail holds exactly the cards that are up",+ seen["cards"] == expected_cards,+ f"cards={seen['cards']} want={expected_cards}; an extra slot is an "+ "overlay mounting when it has nothing to show",+ )++def stub(payload: dict):"""A route handler that answers with `payload`."""@@ -946,6 +1045,9 @@ def main() -> int:"nothing to measure, so every other check is vacuous",)measure(page, f"{size} {name} collapsed")+ if path == "/":+ # Both update cards up, indicator off by default (#8346).+ check_downloads_absent(page, f"{size} {name}", 2)page.screenshot(path = str(ART / f"{size}-{path.strip('/') or 'new-chat'}.png"))toggle = page.locator('[data-testid="web-update-release-notes-toggle"]')@@ -1044,7 +1146,9 @@ def main() -> int:)check(f"{width}x{height}: the rail is still in its bottom-right corner",- seen is not None and seen["fromBottom"] == 16 and seen["fromRight"] == 16,+ seen is not None+ and seen["fromBottom"] == CORNER_INSET_PX+ and seen["fromRight"] == CORNER_INSET_PX,f"{seen}, so the rail has left the corner it is anchored to",)check(