Skip to content

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.

Read the sidebar and reasoning contracts as claims, not as literals (#11404)

Daniel Han47e595c7d97f
diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.css
index 98728bef45d..01a7d4d2094 100644
--- a/studio/frontend/src/index.css
+++ b/studio/frontend/src/index.css
@@ -1193,6 +1193,13 @@ html[data-chat-font] .aui-root {
.sidebar-row-action.is-unpin-action {
right: 1.875rem;
padding-right: 0.125rem;
+ /* The base pl-2 faces the options button, which is what opens the gap between the two
+ icons. On the pin there is nothing to its left but the title, so that padding is
+ dead space: invisible, but inside the button, and sidebar-touch-reveal makes the
+ button clickable on a coarse pointer. It put 8px of the title under the pin on
+ project rows, where a tap pinned the chat instead of opening it. Nothing moves
+ visually; the glyph is positioned from the right. */
+ padding-left: 0;
}
.sidebar-row-action.is-unpin-action + .sidebar-row-action {
padding-left: 0;
diff --git a/tests/studio/test_chat_response_details_ui_contract.py b/tests/studio/test_chat_response_details_ui_contract.py
index 0838b5127ed..ba8dbf7861f 100644
--- a/tests/studio/test_chat_response_details_ui_contract.py
+++ b/tests/studio/test_chat_response_details_ui_contract.py
@@ -24,6 +24,331 @@ CHAT_TAB_TSX = REPO / "studio/frontend/src/features/settings/tabs/chat-tab.tsx"
EN_LOCALE_TS = REPO / "studio/frontend/src/i18n/locales/en.ts"
+# A className this reader cannot resolve. Distinct from None, which means the element carries
+# no className at all, because the two want opposite treatment: absent is a fact to assert on,
+# unreadable is a stale guard that must not quietly pass.
+_UNREADABLE = "\x00unreadable"
+
+
+def _class_list(source: str, marker: str) -> str | None:
+ """The className of the JSX element whose opening tag contains `marker`.
+
+ The opening tag is found first and the attribute read out of it, rather than matching
+ `marker` and `className` as neighbours. JSX attribute order carries no meaning, so a
+ `ref`, an `aria-*` or a test id inserted between them changes nothing about the element
+ and must not fail a guard that is here to stop unrelated refactors reddening main.
+
+ Comments come out of the whole source first. A commented-out element still contains its
+ own `<`, so slicing from the marker found the tag inside `{/* ... */}` and reported the
+ class list of something the page does not render.
+ """
+ source = _without_block_comments(source)
+ start = source.find(marker)
+ if start == -1:
+ return None
+ # Back up to the `<` that opens the element before reading forward. Scanning only the
+ # suffix after the marker misses `className` written BEFORE it, which is the same
+ # attribute-order assumption one level down.
+ opens = source.rfind("<", 0, start + len(marker))
+ if opens == -1:
+ return None
+ # The first `>` is not the end of the tag. An expression prop can contain one, and an
+ # arrow function is the ordinary case: `onClick={() => ...}` ends the tag early and the
+ # class list disappears. Only a `>` outside the JSX expression braces closes it.
+ depth, end = 0, None
+ for index in range(opens, len(source)):
+ char = source[index]
+ if char == "{":
+ depth += 1
+ elif char == "}":
+ depth -= 1
+ elif char == ">" and depth == 0:
+ end = index
+ break
+ if end is None:
+ return None
+ opening = _without_comments(source[opens : end + 1])
+ # A spread can carry className, and nothing here can say what is in it. An element that
+ # spreads props is an element whose class list is unknown, which is not the same as one
+ # that states none: returning None would send the caller back to the base classes and
+ # let an override through.
+ #
+ # Only a spread AFTER the explicit attribute, though. JSX applies attributes in order, so
+ # `{...props} className="min-w-0"` ends with the explicit one whatever the spread holds,
+ # and refusing that shape would fail a safe refactor rather than catch anything.
+ if _spread_overrides(opening, "className"):
+ return _UNREADABLE
+ # On an attribute boundary, so that the name has to be the whole attribute. Unanchored,
+ # `data-className="flex min-w-0"` matched on its suffix and its tokens came back as the
+ # element's rendered classes, which the browser never applies.
+ literal = re.search(r'(?:^|[\s{])className="([^"]*)"', opening)
+ if literal:
+ return literal.group(1)
+ # An expression-valued className, `className={cn(...)}` or `className={"min-w-max"}`.
+ # Its quoted pieces are what tailwind-merge sees, in this order; anything else in the
+ # expression is beyond a reader like this one. Returning None here would be worse than
+ # useless: the caller would fall back on the base classes and pass while the call site
+ # overrode them, so an expression with no readable piece has to say so instead.
+ expression = re.search(r"(?:^|[\s{])className=\{", opening)
+ if not expression:
+ return None
+ # Only the className expression, closed by its own brace. Reading to the end of the tag
+ # swept up quoted strings belonging to later attributes and called them classes.
+ depth, body = 1, None
+ for index in range(expression.end(), len(opening)):
+ if opening[index] == "{":
+ depth += 1
+ elif opening[index] == "}":
+ depth -= 1
+ if depth == 0:
+ body = opening[expression.end() : index]
+ break
+ if body is None:
+ return _UNREADABLE
+ # Strip a single cn(...) wrapper, then require every argument to be a plain string
+ # literal. Anything else is a value this reader cannot evaluate: a conditional picks one
+ # branch and flattening both reads the wrong one, and a bare identifier could be
+ # anything at all. Either way the honest answer is that the class list is unknown, not
+ # that it is whatever literals happen to be lying around.
+ body = body.strip()
+ wrapper = re.fullmatch(r"cn\((.*)\)", body, re.S)
+ if wrapper:
+ body = wrapper.group(1)
+ arguments = [part.strip() for part in _split_arguments(body)]
+ if not arguments or any(not re.fullmatch(r'"[^"]*"', part) for part in arguments):
+ return _UNREADABLE
+ return " ".join(part[1:-1] for part in arguments)
+
+
+def _split_arguments(body: str) -> list[str]:
+ """`body` split on top-level commas, ignoring those inside brackets or strings."""
+ parts, depth, quoted, current = [], 0, False, []
+ for char in body:
+ if quoted:
+ current.append(char)
+ if char == '"':
+ quoted = False
+ continue
+ if char == '"':
+ quoted = True
+ elif char in "([{":
+ depth += 1
+ elif char in ")]}":
+ depth -= 1
+ elif char == "," and depth == 0:
+ parts.append("".join(current))
+ current = []
+ continue
+ current.append(char)
+ if current:
+ parts.append("".join(current))
+ return [part for part in parts if part.strip()]
+
+
+def _assert_only_shrinks(tokens: list[str], what: str, evidence: str) -> None:
+ """Exactly one min-width utility, unqualified, and it is `min-w-0`.
+
+ An earlier version of this tried to work out which min-width WINS: last in `cn` order,
+ per responsive variant, with `!important` beating an ordinary utility written after it.
+ Every rule it gained was correct and the next one was still missing, because deciding
+ that question properly is tailwind-merge plus the cascade, and a test file is the wrong
+ place to keep a second copy of either.
+
+ So it does not decide. One min-width, no variants, no importance markers, and it has to
+ be the shrinking one. That is stricter than the framework: `min-w-0 md:min-w-0` really
+ does shrink everywhere and is refused anyway. It is refused LOUDLY, saying that this
+ guard does not adjudicate precedence, which is a message someone can act on, and it
+ cannot quietly approve a layout nobody checked. Between a guard that is occasionally
+ inconvenient and one that is occasionally wrong, this picks the first.
+ """
+ # min-width is necessary but not sufficient. The trigger shrinks because it is a flex
+ # item that is allowed to: `shrink-0` or `flex-none` alongside `min-w-0` stops it
+ # shrinking inside the header and lets a long summary widen the thread, with every
+ # min-width check here still green. Refused rather than weighed, like the rest of this.
+ pinned = [
+ token
+ for token in tokens
+ # Only the ones that actually disable shrinking. `grow-0` sets flex-grow and leaves
+ # flex-shrink alone, so an element with min-w-0 still shrinks normally; refusing it
+ # would fail a correct flex-growth change for a defect it does not have.
+ if re.fullmatch(r"(?:\S*:)?!?(?:shrink-0|flex-none)!?", token)
+ ]
+ assert not pinned, (
+ f"{what} carries {sorted(set(pinned))}, which stops it shrinking however low its "
+ f"min-width goes, so the summary widens its row instead. {evidence}"
+ )
+ widths = [token for token in tokens if _is_min_width(token)]
+ assert widths, (
+ f"{what} states no min-width at all, so whether it shrinks below its content is left "
+ f"to whatever the element defaults to. {evidence}"
+ )
+ # By distinct utility: the same class written on both the base and the call site is a
+ # duplicate, not a conflict, and tailwind-merge collapsing it changes nothing.
+ assert set(widths) == {"min-w-0"}, (
+ f"{what} carries min-width utilities this guard will not adjudicate between: "
+ f"{sorted(set(widths))}. Which one wins is tailwind-merge's answer and then the cascade's, and "
+ f"getting that wrong in either direction is worse than refusing: a variant-qualified "
+ f"or important min-width, or more than one of them, has to be reduced to a single "
+ f"unqualified min-w-0 for this to pass. {evidence}"
+ )
+
+
+# `[min-width:max-content]` sets the same property by another spelling, and a guard that
+# only knows `min-w-*` reads a class list containing it as stating nothing. Splitting on the
+# LAST colon breaks it too, since the value contains one, so the arbitrary form is matched
+# before any variant is stripped.
+_ARBITRARY_MIN_WIDTH = re.compile(r"(?:^|:)!?\[min-width:[^\]]*\]!?$")
+
+
+def _is_min_width(token: str) -> bool:
+ if _ARBITRARY_MIN_WIDTH.search(token.removeprefix("!")):
+ return True
+ # Variants are separated by `:`, but an arbitrary value can hold one of its own:
+ # `min-w-[length:max-content]` compiles to `min-width: max-content` and drops an earlier
+ # `min-w-0` through tailwind-merge, while splitting on the last `:` left `max-content]`
+ # and this reader saw no min-width at all. Bracketed spans are masked before the split.
+ masked = re.sub(r"\[[^\]]*\]", lambda found: "\x00" * len(found.group(0)), token)
+ _, _, tail = masked.rpartition(":")
+ utility = token[len(masked) - len(tail) :]
+ return utility.removeprefix("!").removesuffix("!").startswith("min-w-")
+
+
+def _cn_literals(source: str, anchor: str) -> str | None:
+ """The string literals of the `cn(...)` call containing `anchor`, joined in order.
+
+ `className` itself is expected among the arguments: that is the caller's contribution,
+ read separately. Any OTHER unresolved argument means this cannot say what the element
+ composes to, which is _UNREADABLE rather than silence.
+
+ Comments out first, for the same reason `_class_list` does it: a dead `cn(...)` left in a
+ block comment sits before the live component, so the anchor was found there and this
+ validated classes nothing composes.
+ """
+ source = _without_block_comments(source)
+ at = source.find(anchor)
+ if at == -1:
+ return None
+ opens = source.rfind("cn(", 0, at)
+ if opens == -1:
+ return None
+ depth, closes = 0, None
+ for index in range(opens + 2, len(source)):
+ if source[index] == "(":
+ depth += 1
+ elif source[index] == ")":
+ depth -= 1
+ if depth == 0:
+ closes = index
+ break
+ if closes is None:
+ return _UNREADABLE
+ pieces, forwards = [], False
+ for argument in _split_arguments(source[opens + len("cn(") : closes]):
+ argument = argument.strip()
+ literal = re.fullmatch(r'"([^"]*)"', argument)
+ if literal:
+ pieces.append(literal.group(1))
+ elif argument == "className":
+ forwards = True
+ else:
+ return _UNREADABLE
+ # The caller's classes have to actually arrive. Without `className` among the arguments
+ # the component composes from its base alone, and the caller's contribution, which the
+ # test adds to the order afterwards, reaches nothing. Reading the base and crediting the
+ # call site anyway is how a trigger that stopped forwarding would keep passing.
+ if not forwards:
+ return _UNREADABLE
+ return " ".join(pieces)
+
+
+def _opening_tags(source: str, marker: str) -> list[str]:
+ """Every opening JSX tag beginning at `marker`, brace-aware."""
+ tags, at = [], source.find(marker)
+ while at != -1:
+ tag = _opening_tag(source[at:], marker)
+ if tag:
+ tags.append(tag)
+ at = source.find(marker, at + len(marker))
+ return tags
+
+
+def _opening_tag(source: str, marker: str) -> str | None:
+ """The opening JSX tag beginning at `marker`, brace-aware.
+
+ `[^>]*` ends at the first `>`, and an arrow function in an earlier prop supplies one, so
+ the tag would come back truncated and the props after it invisible.
+ """
+ opens = source.find(marker)
+ if opens == -1:
+ return None
+ depth = 0
+ for index in range(opens, len(source)):
+ if source[index] == "{":
+ depth += 1
+ elif source[index] == "}":
+ depth -= 1
+ elif source[index] == ">" and depth == 0:
+ return _without_comments(source[opens : index + 1])
+ return None
+
+
+def _without_block_comments(source: str) -> str:
+ """The source with comments removed, block and line alike.
+
+ Line comments matter as much as block ones here: everything below locates JSX by
+ searching the text, so a stale `// <ReasoningBody isStreaming={...} ...>` left above the
+ render is found by `_opening_tags` and read as the live element. The contract then
+ describes a tag that renders nothing while the real one has lost both props.
+
+ `(?<!:)` keeps `https://` out of it, which is the one `//` in this file that is not a
+ comment.
+ """
+ source = re.sub(r"\{?\s*/\*.*?\*/\s*\}?", " ", source, flags = re.S)
+ return "\n".join(re.sub(r"(?<!:)//.*$", "", line) for line in source.splitlines())
+
+
+def _spread_overrides(tag: str, attribute: str) -> bool:
+ """True when `tag` spreads props in a position that can beat an explicit `attribute`.
+
+ JSX applies attributes left to right and the last write wins, so `{...props} name={x}`
+ ends with `x` whatever the spread holds, while `name={x} {...props}` does not. Refusing
+ both would make the guard red on a safe refactor that forwards unrelated props, which is
+ a worse failure than the one it is guarding: it stops correct work.
+
+ A tag with no explicit attribute at all is unknown if it spreads anything, since the
+ spread is then the only thing that could be supplying it.
+ """
+ # At the tag's own attribute level only. An object spread inside another prop, such as
+ # `onClick={() => call({...payload})}`, cannot reach className, and treating it as if it
+ # could made this refuse a tag that is perfectly readable.
+ spreads = []
+ depth = 0
+ for index, char in enumerate(tag):
+ if char == "{":
+ if depth == 0 and re.match(r"\{\s*\.\.\.", tag[index:]):
+ spreads.append(index)
+ depth += 1
+ elif char == "}":
+ depth -= 1
+ if not spreads:
+ return False
+ explicit = re.search(rf"(?:^|[\s{{]){re.escape(attribute)}=", tag)
+ return explicit is None or max(spreads) > explicit.start()
+
+
+def _without_comments(tag: str) -> str:
+ """`tag` with commented-out lines removed.
+
+ A prop commented out is a prop that is not passed, and every check here is a substring
+ test, so leaving the text in place lets a disabled prop satisfy the guard that exists to
+ notice it went away. Only a `//` that begins a line counts, so a `//` inside a value is
+ left alone; `/* ... */` is removed wherever it sits, because between two attributes is
+ exactly where it sits when it is being used to switch a prop off.
+ """
+ kept = [line for line in tag.splitlines() if not line.lstrip().startswith("//")]
+ return re.sub(r"/\*.*?\*/", " ", "\n".join(kept), flags = re.S)
+
+
def test_assistant_more_menu_exposes_response_details_action():
src = THREAD_TSX.read_text(encoding = "utf-8")
assert "MessageResponseDetailsSheet" in src
@@ -117,11 +442,133 @@ def test_response_model_badge_is_user_configurable_and_rendered_once_per_message
assert "group/assistant-message aui-assistant-message-root" in thread_src
assert "pointer-events-none relative h-0" in thread_src
assert "MessageResponseModelBadge" not in reasoning_src
- assert 'className="min-w-0 flex-1"' in reasoning_src
+ # The trigger has to be able to shrink below its content, or a long summary pushes the row
+ # wider than the thread. `min-w-0` grants that. It used to be written `min-w-0 flex-1` on
+ # one element; #11373 moved the filling to a header wrapper and left the shrinking on the
+ # trigger, so pinning the old pair asserted one commit's layout rather than the property.
+ #
+ # Where the utility is written is not the property either. It currently appears twice, in
+ # ReasoningTrigger's base classes and again on the call site, so demanding the call-site
+ # copy would fail a harmless deduplication while the trigger still shrank. Both are read
+ # and either satisfies it.
+ #
+ # Whole class tokens, not a substring: `\b` treats the colon in `md:min-w-0` as a
+ # boundary, so a variant-qualified utility would satisfy a loose match while leaving the
+ # trigger unable to shrink at every width it was not qualified for.
+ # The WHOLE composition inside the component, not its first quoted literal. A second
+ # literal appended after `className` would be effective and invisible to a first-match
+ # read, and an argument this cannot resolve means the composition is unknown.
+ # Bound to the element's className, not merely present in the file. The composition below
+ # is found by its first literal, and a literal says nothing about where it is applied:
+ # `data-className={cn(...)}` is valid JSX that renders none of these classes, so neither
+ # the base composition nor the call site's min-w-0 would reach the DOM while every check
+ # below went on describing them.
+ live = _without_block_comments(reasoning_src)
+ base_tags = [
+ tag for tag in _opening_tags(live, "<Trigger") if 'data-slot="reasoning-trigger"' in tag
+ ]
+ assert base_tags, (
+ 'reasoning.tsx no longer renders a Trigger with data-slot="reasoning-trigger", so the '
+ "base min-w-0 this guard reads belongs to no element on the page"
+ )
+ for tag in base_tags:
+ lookalike = re.search(r"[\w-]className=", tag)
+ assert not lookalike, (
+ f"the reasoning trigger carries {lookalike.group(0)!r} rather than a className, so "
+ f"the classes this guard reads render on nothing: {tag!r}"
+ )
+ applied_to = re.search(r"(?:^|[\s{])className=\{(.*)", tag, re.S)
+ assert applied_to and '"aui-reasoning-trigger' in applied_to.group(1), (
+ f"the reasoning trigger's className is not the composition this guard reads, so "
+ f"what it measures is not what renders: {tag!r}"
+ )
+
+ base = _cn_literals(reasoning_src, '"aui-reasoning-trigger')
+ assert base != _UNREADABLE, (
+ "ReasoningTrigger composes its className from something this guard cannot resolve, "
+ "so it cannot tell what the trigger ends up with. Widen the reader before trusting it"
+ )
+ # That it is rendered at all, before reading what it is given. `_class_list` answers None
+ # both for a call site that passes no className and for one that is not there, and the
+ # component's own function can stay behind unused, so without this the header could stop
+ # rendering the trigger entirely and the checks below would go on describing base classes
+ # that reach nothing.
+ assert "<ReasoningTrigger" in _without_block_comments(reasoning_src), (
+ "ReasoningTrigger is no longer rendered, so the shrinking this test is about belongs "
+ "to an element that is not on the page"
+ )
+ # An inline style beats every utility below it in the cascade, and none of them is read
+ # here. `style={{ minWidth: "max-content" }}` on the trigger leaves both min-w-0 checks
+ # green while long summaries widen the row again, which is the whole defect.
+ header_tags = [
+ tag for tag in _opening_tags(live, "<div") if 'data-slot="reasoning-header"' in tag
+ ]
+ assert header_tags, (
+ 'reasoning.tsx no longer renders a div with data-slot="reasoning-header", so this '
+ "guard cannot tell which element the trigger has to shrink inside"
+ )
+ # The header is a plain div carrying data-slot, not a <ReasoningHeader> component. Naming
+ # the component matched nothing at all, so half of this check was vacuous and an inline
+ # width on the real header went straight through.
+ # The <Trigger> that ReasoningTrigger renders is where the base min-w-0 actually lives, so
+ # it belongs in this loop as much as the call site does: a style there overrides the very
+ # class this test reads, and checking only the call site and the header left it out.
+ # Spreads are refused on the call site and the header, not on the base Trigger: that one
+ # forwards `{...props}` by design, which is how a caller reaches it at all, and the values
+ # arriving through it are exactly what the call-site check above adjudicates. Refusing it
+ # here would fail the shipped component for doing the right thing.
+ for tag in [*_opening_tags(live, "<ReasoningTrigger"), *header_tags]:
+ assert not _spread_overrides(tag, "style"), (
+ f"an element the min-w-0 chain depends on takes a spread that may carry a style, "
+ f"which would outrank the utilities this guard compares: {tag!r}"
+ )
+ for tag in [*_opening_tags(live, "<ReasoningTrigger"), *header_tags, *base_tags]:
+ assert not re.search(r"(?:^|[\s{])style=", tag), (
+ f"an element the min-w-0 chain depends on carries an inline style, which outranks "
+ f"the utilities this guard compares, so the width it computes is not the width "
+ f"that renders: {tag!r}"
+ )
+ call_site = _class_list(reasoning_src, "<ReasoningTrigger")
+ assert call_site != _UNREADABLE, (
+ "the ReasoningTrigger call site passes a className this guard cannot resolve, so it "
+ "cannot tell whether the base min-w-0 survives tailwind-merge. Widen the reader "
+ "before trusting it"
+ )
+ # In `cn(base, className)` order, and the LAST min-w-* wins: cn runs tailwind-merge, so a
+ # call site passing min-w-full or min-w-max drops the base min-w-0 and the trigger stops
+ # shrinking. A union of the two would still hold the base token and call that fine.
+ ordered = (base.split() if base else []) + (call_site.split() if call_site else [])
+ assert ordered, (
+ "neither ReasoningTrigger's base classes nor its call site carries a class list this "
+ "can read, so this guard cannot see the trigger's layout at all"
+ )
+ _assert_only_shrinks(
+ ordered,
+ "the reasoning trigger",
+ f"Base classes: {base!r}. Call site: {call_site!r}",
+ )
+ header = _class_list(reasoning_src, 'data-slot="reasoning-header"')
+ assert header is not None, "the reasoning header row no longer carries a className"
+ assert header != _UNREADABLE, (
+ "the reasoning header row carries a className this guard cannot resolve, so it "
+ "cannot tell whether the row still shrinks. Widen the reader before trusting it"
+ )
+ assert "flex" in header.split(), (
+ f"the header row holding the trigger is no longer a flex row, so the trigger's own "
+ f"shrinking is not what decides the layout any more: {header!r}"
+ )
+ # Read the same way as the trigger: a header that shrinks everywhere except above one
+ # breakpoint puts the overflow back one level up at exactly those widths.
+ _assert_only_shrinks(
+ header.split(), "the header row holding the trigger", f"Classes: {header!r}"
+ )
def test_reasoning_keeps_streaming_height_cap_through_automatic_collapse():
- src = REASONING_TSX.read_text(encoding = "utf-8")
+ # Stripped once, here, rather than at each lookup. Every assertion below is about what
+ # the file DOES, and commented-out code does nothing, so reading the live text is the
+ # precondition for all of them rather than a precaution for some.
+ src = _without_block_comments(REASONING_TSX.read_text(encoding = "utf-8"))
assert "const [retainStreamingHeight, setRetainStreamingHeight]" in src
assert "setRetainStreamingHeight(false)" in src
@@ -135,7 +582,78 @@ def test_reasoning_keeps_streaming_height_cap_through_automatic_collapse():
assert "const closeDelay = GRID_COLLAPSE_REASONING_ENABLED" in src
assert "? ANIMATION_DURATION + CLOSE_FALLBACK_MARGIN_MS" in src
assert ": ANIMATION_DURATION;" in src
- assert "streaming={isReasoningStreaming || retainStreamingHeight}" in src
+ # The cap is `streaming || retained`, and #11373 moved the render down a level: the state
+ # lives here and is handed to the child as a prop, which then ORs it with its own
+ # streaming flag. Which component evaluates it is layout; that it is still ORed, and that
+ # the retained flag actually reaches the evaluation, is the claim.
+ # On the element that receives it, not anywhere in the file. The same text in a comment,
+ # or on some other element, reads identically to a file-wide search and hands nothing
+ # over; ReasoningText would then OR in its own default-false prop and the cap is lost.
+ # ReasoningBody is rendered more than once, and the one that matters is the one holding
+ # this state: it passes isStreaming={isReasoningStreaming}, the flag whose end is what
+ # the retained height is bridging. Every such call has to hand the retained flag over.
+ holders = [
+ tag
+ for tag in _opening_tags(src, "<ReasoningBody")
+ # On an attribute boundary, like the retained flag below. Both props are optional, so
+ # `data-isStreaming={isReasoningStreaming}` satisfies a substring test while
+ # ReasoningBody receives no isStreaming at all: the tag is still selected as a holder,
+ # every assertion below still passes, and the live stream is no longer capped.
+ if re.search(r"(?:^|[\s{])isStreaming=\{isReasoningStreaming\}", tag)
+ ]
+ assert holders, (
+ "no ReasoningBody receives isReasoningStreaming any more, so this guard cannot tell "
+ "which render is the one whose collapse the retained height exists to smooth"
+ )
+ # A spread can supply the same prop and, written after it, wins. Nothing here can say
+ # what is in one, so a holder that spreads is refused rather than read.
+ # BOTH props, not the retained flag alone. What is being kept is the OR of the two, so a
+ # spread that replaces `isStreaming` loses just as much: written between the two
+ # attributes, `{...{ isStreaming: false }}` leaves the retained flag untouched and this
+ # check green while ReasoningText stops seeing the live stream and renders uncapped until
+ # the retained state catches up. `isStreaming` is also what picks the holders above, so a
+ # spread overriding it makes the selection itself wrong.
+ spreading = [
+ tag
+ for tag in holders
+ if any(_spread_overrides(tag, prop) for prop in ("isStreaming", "retainStreamingHeight"))
+ ]
+ assert not spreading, (
+ f"a ReasoningBody holding this state spreads props, so whether the streaming flags it "
+ f"is handed survive depends on what the spread contains, which this guard cannot "
+ f"resolve: {spreading!r}"
+ )
+ # On an attribute boundary. Both props are optional, so `data-retainStreamingHeight=`
+ # satisfies a substring search while the component falls back on its default of false.
+ missing = [
+ tag
+ for tag in holders
+ if not re.search(r"(?:^|[\s{])retainStreamingHeight=\{retainStreamingHeight\}", tag)
+ ]
+ assert not missing, (
+ f"the retained-height flag no longer reaches the component that renders the block, "
+ f"so nothing can OR it into the streaming cap: {missing!r}"
+ )
+ # On ReasoningText specifically. It is the element that writes data-streaming and so owns
+ # the height cap; the same OR on a sibling reads identically here and caps nothing.
+ tag = _opening_tag(src, "<ReasoningText")
+ assert tag, "ReasoningText is no longer rendered, so nothing here caps the height"
+ # Same ground as the holder above, and it has to be said again here: JSX takes the last
+ # write of a prop, so a spread after `streaming=` decides the cap and the explicit text
+ # this guard reads goes on satisfying it.
+ assert not _spread_overrides(tag, "streaming"), (
+ f"ReasoningText spreads props after its streaming prop, so whether the cap it is "
+ f"given survives "
+ f"depends on what the spread contains, which this guard cannot resolve: {tag!r}"
+ )
+ # The left operand has to be the component's own streaming input. `\w+` accepted any
+ # identifier, so `streaming={somethingElse || retainStreamingHeight}` passed while an
+ # actively streaming block went uncapped whenever the retained flag was false.
+ assert re.search(r"(?:^|[\s{])streaming=\{isStreaming \|\| retainStreamingHeight\}", tag), (
+ f"ReasoningText's streaming prop no longer ORs in retainStreamingHeight, so the block "
+ f"collapses to its idle height the moment streaming stops, which is the jump this "
+ f"test exists for: {tag!r}"
+ )
def test_reasoning_clears_manual_open_on_a_new_stream():
@@ -144,13 +662,145 @@ def test_reasoning_clears_manual_open_on_a_new_stream():
isOpen is `(streaming && !dismissed) || manualOpen` and manualOpen is only
settable while idle, so the new-stream reset has to clear it too.
"""
- src = REASONING_TSX.read_text(encoding = "utf-8")
+ src = _without_block_comments(REASONING_TSX.read_text(encoding = "utf-8"))
- marker = "setDismissedWhileStreaming(false)"
- start = src.find(marker)
- assert start != -1, "new-stream reset effect is missing"
- effect = src[src.rfind("useEffect(() => {", 0, start) : src.find("});", start)]
- assert "setManualOpen(false)" in effect
+ # Which state holds the manual answer is read, not assumed. The previous form of this test
+ # pinned `setManualOpen(false)`, and when #11433 replaced the `manualOpen` /
+ # `dismissedWhileStreaming` pair with one nullable override the rename read as the reset
+ # having been deleted. The override is identified the way the component itself identifies
+ # it: it is the value `resolveReasoningOpen` is given as its override.
+ opener = re.search(r"resolveReasoningOpen\(\{(.*?)\}\)", src, re.S)
+ assert opener, (
+ "reasoning.tsx no longer resolves its open state through resolveReasoningOpen, so "
+ "this guard cannot tell which state holds a hand toggle's answer"
+ )
+ field = re.search(
+ r"(?:^|,)\s*override\s*(?::\s*([A-Za-z_$][\w$]*))?\s*(?:,|$)", opener.group(1)
+ )
+ assert field, (
+ f"resolveReasoningOpen is no longer passed an override, so nothing here outranks the "
+ f"visibility setting and a hand toggle has nowhere to live: {opener.group(1)!r}"
+ )
+ held = field.group(1) or "override"
+ # The identifier holding the live streaming flag, read the same way, because the predicate
+ # below has to be handed it first.
+ streaming_field = re.search(
+ r"(?:^|,)\s*isStreaming\s*(?::\s*([A-Za-z_$][\w$]*))?\s*(?:,|$)", opener.group(1)
+ )
+ assert streaming_field, (
+ f"resolveReasoningOpen is no longer passed an isStreaming, so this guard cannot tell "
+ f"which value is the live stream: {opener.group(1)!r}"
+ )
+ held_streaming = streaming_field.group(1) or "isStreaming"
+ setter = re.search(rf"const \[{re.escape(held)},\s*(set\w+)\]\s*=\s*useState", src)
+ assert setter, (
+ f"{held!r} reaches resolveReasoningOpen but is not a useState in reasoning.tsx, so "
+ f"this guard cannot tell what writing it looks like"
+ )
+ writes = setter.group(1)
+
+ # It is the hand toggle that writes it. Without this the override could be some derived
+ # value the reader never sets, and clearing it would say nothing about a pinned block.
+ toggle_at = src.find("resolveReasoningToggle(")
+ assert toggle_at != -1, "reasoning.tsx no longer resolves its open toggle, so nothing here "
+ handler = src[src.rfind("useCallback(", 0, toggle_at) : src.find("\n );", toggle_at)]
+ # With the value the toggle RESOLVED, not merely called with something. `setOverride(null)`
+ # in the handler satisfies "the setter is invoked" while no hand toggle is ever remembered,
+ # which makes the new-round reset below guard nothing at all.
+ resolved = re.search(rf"{re.escape(writes)}\(\s*([A-Za-z_$][\w$.]*)\s*\)", handler)
+ assert resolved and resolved.group(1) != "null", (
+ f"the open toggle does not store the override it resolved: it writes "
+ f"{resolved.group(1) if resolved else 'something this guard cannot read'!r}. A hand "
+ f"toggle is then never remembered, and clearing the override on a new round guards "
+ f"nothing"
+ )
+ # Its `override`, by name. Requiring only the `next.` prefix let
+ # `setOverride(next.releaseStreamingHeight)` pass: both fields are booleans so it
+ # type-checks, but reopening a hand-closed block whose setting defaults open wants
+ # override true while releaseStreamingHeight is false, and the block stays shut.
+ answer = re.search(r"const (\w+) = resolveReasoningToggle\(", handler)
+ assert answer and resolved.group(1) == f"{answer.group(1)}.override", (
+ f"the open toggle writes {resolved.group(1)!r}, which is not the answer "
+ f"resolveReasoningToggle returned, so what the reader asked for and what is stored "
+ f"can differ"
+ )
+
+ # And a new round clears it. Regenerate reuses this component instance, so without this a
+ # block opened by hand over the last answer stays pinned open over the next one.
+ round_at = src.find("startsNewReasoningRound(")
+ assert round_at != -1, (
+ "reasoning.tsx no longer asks whether a new reasoning round started, so nothing "
+ "distinguishes a fresh stream from the end of the last one"
+ )
+ # Used positively, and as the whole condition. Locating the call and then reading the block
+ # after it says nothing about the sense in which it was asked:
+ # `if (!startsNewReasoningRound(...)) { setOverride(null); }` clears the override on every
+ # transition EXCEPT a new round, which is the exact inverse of the contract, and it read as
+ # green. Requiring `if (` to sit immediately before the call rejects the negation and any
+ # other prefix; a condition that grows a second term has to teach this guard about it
+ # rather than slipping past.
+ assert re.search(r"if\s*\(\s*$", src[:round_at]), (
+ "the new reasoning round is not asked as `if (startsNewReasoningRound(...))`. Negated "
+ "or combined with another term it can clear the override on the transitions that are "
+ "not a new round, and leave the one that is untouched, which is the inverse of what "
+ "this guards"
+ )
+ # The brace has to be this condition's own. `_without_block_comments` strips the braces
+ # around a comment along with it, so a branch whose body is only a comment loses its `{}`
+ # entirely, and a scan for the next `{` then runs on into whatever block follows and reads
+ # that one instead. Found by sabotage: emptying the new-round branch left this guard
+ # reading the visibility-change branch, which clears the override too, so the guard passed
+ # while the reset it exists for was gone.
+ # In the order the predicate reads them. It is `isStreaming && !wasStreaming`, so swapping
+ # the two type-checks and inverts the meaning: it then fires when a round ENDS, leaving a
+ # hand-set override alive into the next one, which is the defect this whole test is about.
+ # The current flag is the one resolveReasoningOpen is given; the previous one is the state
+ # seeded from it.
+ previous = re.search(rf"const \[(\w+), set\w+\] = useState\({re.escape(held_streaming)}\)", src)
+ assert previous, (
+ f"reasoning.tsx no longer keeps the previous streaming value in a useState seeded "
+ f"from {held_streaming!r}, so this guard cannot tell which argument is which"
+ )
+ arguments = re.match(r"startsNewReasoningRound\(([^()]*)\)", src[round_at:])
+ assert arguments and [part.strip() for part in arguments.group(1).split(",")] == [
+ held_streaming,
+ previous.group(1),
+ ], (
+ f"startsNewReasoningRound is called with "
+ f"{arguments.group(1).strip() if arguments else 'arguments this guard cannot read'!r}. "
+ f"It reads (current, previous) and returns true only when a round begins; the other "
+ f"order type-checks and fires when one ends, leaving the override alive into the next"
+ )
+ # Nothing between the call and the brace but the `)` that closes the `if`. That rejects the
+ # other way to invert it, `if (startsNewReasoningRound(...) === false) {`, which the older
+ # form of this check let through because it only refused a statement or block boundary.
+ opened = src.find("{", round_at)
+ assert opened != -1 and re.fullmatch(
+ r"startsNewReasoningRound\([^()]*\)\s*\)\s*", src[round_at:opened]
+ ), (
+ "the branch taken when a new reasoning round starts is not a block this guard can "
+ "read: something sits between the predicate and the brace, so the block that follows "
+ "runs under a condition other than the plain question this expects"
+ )
+ depth, closed = 0, None
+ for index in range(opened, len(src)):
+ if src[index] == "{":
+ depth += 1
+ elif src[index] == "}":
+ depth -= 1
+ if depth == 0:
+ closed = index
+ break
+ assert closed is not None, "the new-round branch in reasoning.tsx is unterminated"
+ # As a statement of the branch itself, not merely somewhere inside it. `if (false)
+ # setOverride(null)` and a nested block both satisfy a substring search while a
+ # hand-opened block stays pinned across a regenerate, which is the whole contract.
+ statements = [piece.strip() for piece in src[opened + 1 : closed].split(";")]
+ assert f"{writes}(null)" in statements, (
+ f"a new reasoning round does not clear {held!r}. A block the reader opened by hand "
+ f"during the previous round keeps its override, so it stays pinned open over the "
+ f"next answer whatever the Thinking setting says"
+ )
def test_response_details_metadata_is_persisted_without_backend_schema_change():
diff --git a/tests/studio/test_desktop_reliability_frontend_contract.py b/tests/studio/test_desktop_reliability_frontend_contract.py
index a5762363503..fa3f3ee060d 100644
--- a/tests/studio/test_desktop_reliability_frontend_contract.py
+++ b/tests/studio/test_desktop_reliability_frontend_contract.py
@@ -3,6 +3,7 @@
"""Static contracts for focused packaged-desktop reliability behavior."""
+import functools
import re
from pathlib import Path
from tests.studio._js_source import (
@@ -852,6 +853,860 @@ def test_chat_sidebar_rows_are_compact_without_vertical_padding():
assert 'variant === "project" ? "pl-[39px]" : "pl-3"' in block
+def _resolve_classes(source: str, expression: str, variant: str) -> str | None:
+ """`expression` as the class string it yields for `variant`, or None if unreadable.
+
+ Every argument has to resolve. Collecting the quoted literals and ignoring the rest is
+ what let the pin's own `cn(..., REVEAL_WITH_OPEN_MENU_PROJECT_CHAT)` read as complete:
+ a constant supplying `sidebar-row-action`, an `is-*` modifier or a positioning utility
+ would have been invisible, and the button skipped or its reach understated with the
+ contract still green.
+
+ Four forms are read, and anything else is None: a literal, `cn(...)` over readable
+ arguments, a ternary on `variant === "..."`, and an identifier defined as a const in this
+ file, which is resolved recursively. `undefined` and a plain conditional's short-circuit
+ contribute nothing, which is what they do.
+ """
+ expression = expression.strip().rstrip(",").strip()
+ if not expression or expression == "undefined":
+ return ""
+ literal = re.fullmatch(r'"([^"]*)"', expression)
+ if literal:
+ return literal.group(1)
+ call = re.fullmatch(r"cn\((.*)\)", expression, re.S)
+ if call:
+ parts = []
+ for argument in _cn_arguments(call.group(1)):
+ piece = _resolve_classes(source, argument, variant)
+ if piece is None:
+ return None
+ parts.append(piece)
+ return " ".join(part for part in parts if part)
+ branched = re.match(r'\s*variant\s*===\s*"(\w+)"\s*\?', expression, re.S)
+ if branched:
+ marks = _operators(expression[branched.end() :])
+ pairing = next((at for at, token in marks if token == ":"), None)
+ if pairing is None:
+ return None
+ rest = expression[branched.end() :]
+ taken = rest[:pairing] if branched.group(1) == variant else rest[pairing + 1 :]
+ return _resolve_classes(source, taken, variant)
+ identifier = re.fullmatch(r"[A-Za-z_$][\w$]*", expression)
+ if identifier:
+ definition = re.search(rf"const {re.escape(expression)} =(.*?);\n", source, re.S)
+ if not definition:
+ return None
+ return _resolve_classes(source, definition.group(1), variant)
+ return None
+
+
+def _spread_may_supply(tag: str, attribute: str = "className") -> bool:
+ """True when a top-level JSX spread could be supplying or replacing *attribute*.
+
+ A spread's contents are not resolvable here, and both ways it can matter are silent. With
+ no explicit `className`, a spread may be the only thing supplying one, and this reader
+ returned "" for that tag so `_labelled_actions` skipped the action entirely: a pin handed
+ `{...{ className: "sidebar-row-action sidebar-touch-reveal right-40" }}` left the reach
+ calculation altogether while the shared options button kept every later assertion
+ satisfied. With an explicit `className`, only a spread written AFTER it can override, since
+ JSX applies attributes left to right and the last write wins.
+ """
+ spreads, depth = [], 0
+ for index, char in enumerate(tag):
+ if char == "{":
+ if depth == 0 and re.match(r"\{\s*\.\.\.", tag[index:]):
+ spreads.append(index)
+ depth += 1
+ elif char == "}":
+ depth -= 1
+ if not spreads:
+ return False
+ explicit = re.search(rf"(?:^|[\s{{]){re.escape(attribute)}=", tag)
+ return explicit is None or max(spreads) > explicit.start()
+
+
+def _button_classes(source: str, tag: str, variant: str) -> str | None:
+ """The classes a `<button>` tag ends up with for `variant`, or None if unreadable."""
+ if _spread_may_supply(tag):
+ return None
+ # A suffixed lookalike is refused, not read as absent. `data-className={cn(...)}` is not a
+ # className, so the boundary above correctly declines to read it, but returning "" then
+ # said "this button carries no classes" and `_labelled_actions` skipped it as not a row
+ # action. The pin can vanish from the reach calculation that way while still rendering,
+ # now with none of the classes that position or reveal it, and the shared options button
+ # keeps every later assertion satisfied.
+ lookalike = re.search(r"[\w-]className=", tag)
+ assert not lookalike, (
+ f"a button in renderChatSidebarItem carries {lookalike.group(0)!r} rather than a "
+ f"className. It renders with none of the classes that string holds, and this guard "
+ f"would otherwise read it as a button that simply has no classes: {tag!r}"
+ )
+ match = re.search(r"(?:^|[\s{])className=(\{.*?\}|\"[^\"]*\")", tag, re.S)
+ if not match:
+ return ""
+ value = match.group(1).strip()
+ if value.startswith('"'):
+ return value.strip('"')
+ return _resolve_classes(source, value[1:-1], variant)
+
+
+def _spacing_rem(live_css: str) -> float | None:
+ """The rem one Tailwind spacing unit is worth, read from the theme's `--spacing`.
+
+ Every `pr-N` here is N of these, while the pin's offset and padding are stated in the
+ stylesheet as fixed rem. Assuming 0.25 made the two comparable only by coincidence: set
+ `--spacing: 0.20rem` and `pr-14` buys 2.8rem where the pin still needs 3.5, so the action
+ overlaps the title while this arithmetic, done in assumed units, says it does not.
+
+ Every declaration has to agree. More than one value means the answer depends on which
+ theme block is in force, which this guard does not model.
+ """
+ stated = {match.group(1) for match in re.finditer(r"--spacing:\s*([\d.]+)rem\s*;", live_css)}
+ return float(stated.pop()) / 1 if len(stated) == 1 else None
+
+
+def _as_spacing_units(cls: str, spacing: float) -> str:
+ """`pr-[78px]` as `pr-19.5`, so an arbitrary gutter is compared rather than refused.
+
+ The checks below compare `pr-N`, where N counts Tailwind spacing units of 0.25rem. A row
+ that states its touch gutter as an exact pixel value is saying the same thing in another
+ spelling, and refusing it made a correct row (#11408's spinner column, `pr-[78px]`) fail a
+ guard about a defect it does not have.
+
+ Only px and rem convert, and only on `pr-`: those are the two the arithmetic here is
+ defined in. Anything else (`%`, `calc()`, `var()`) resolves against something this cannot
+ see, so it is left alone for the refusal below to catch. Left alone rather than dropped,
+ which is the point: an unconvertible value must still reach a check that says so.
+ """
+ match = re.fullmatch(r"((?:\S*:)?pr)-\[(\d+(?:\.\d+)?)(px|rem)\]", cls)
+ if not match:
+ return cls
+ prefix, amount, unit = match.group(1), float(match.group(2)), match.group(3)
+ units = amount / 16 / spacing if unit == "px" else amount / spacing
+ return f"{prefix}-{units:g}"
+
+
+def _own_declarations(live_css: str, selector: str) -> str | None:
+ """One rule's own body, with any rule nested inside it removed.
+
+ Brace-matched rather than read as `[^}]*`, which stops at the first `}` and so takes in a
+ nested rule's selector and declarations while cutting the outer rule short.
+ `.sidebar-row-action` has such a nested rule, `.sidebar-touch-reveal`, so the lazy form was
+ reading part of a different rule as if it belonged to this one.
+ """
+ start = re.search(rf"{re.escape(selector)}\s*\{{", live_css)
+ return None if not start else _declarations_at(live_css, start.end() - 1)
+
+
+def _declarations_at(live_css: str, brace: str | int) -> str | None:
+ """The body of the rule whose opening brace is at *brace*, minus any nested rule."""
+ depth = 0
+ for index in range(brace, len(live_css)):
+ if live_css[index] == "{":
+ depth += 1
+ elif live_css[index] == "}":
+ depth -= 1
+ if depth == 0:
+ return re.sub(r"[^{}]*\{[^{}]*\}", " ", live_css[brace + 1 : index])
+ return None
+
+
+def _modifier_rules(live_css: str) -> dict[str, str]:
+ """Every `.sidebar-row-action.is-*` rule the stylesheet defines, as its own declarations."""
+ rules: dict[str, str] = {}
+ for match in re.finditer(r"\.sidebar-row-action\.(is-[\w-]+)\s*\{", live_css):
+ body = _declarations_at(live_css, match.end() - 1)
+ if body is None:
+ continue
+ # Joined in source order, not replaced. A selector may appear more than once, and CSS
+ # keeps an earlier declaration for any property the later rule does not restate: one
+ # rule setting `right: 5rem` followed by another setting only `color` still renders at
+ # 5rem. Overwriting recorded the second rule alone, so the offset fell back to the
+ # base and the action overlapped the title with this green. Joining also means a
+ # property genuinely restated appears twice, which `_sole_measure` then refuses rather
+ # than resolving, as it does within a single rule.
+ rules[match.group(1)] = f"{rules.get(match.group(1), '')}\n{body}"
+ return rules
+
+
+# What else in the same rule can set the edge this guard measures. A shorthand overrides the
+# longhand it contains, so `padding: 0 5rem` beats a parsed `pr-1.5` and `inset: 0 5rem` beats
+# a parsed `right`. Reading the longhand and ignoring these reported a reach that does not
+# render. Tailwind's own shorthands are listed beside the CSS ones because `@apply p-20` is the
+# same statement written another way.
+_SHORTHANDS = {
+ "pr": (("padding",), ("p", "px", "pe")),
+ "pl": (("padding",), ("p", "px", "ps")),
+ "right": (("inset",), ("inset", "inset-x")),
+}
+
+
+def _sole_measure(body: str, utility: str, prop: str, spacing: float) -> float | None | str:
+ """One rule's value for a measure: the number, None if unreadable, "" if it states none.
+
+ Every declaration is collected, because CSS resolves a repeat to the last and a
+ first-match read reports the first. Two readable values are refused rather than resolved:
+ which one wins also depends on specificity and on where Tailwind emits the utility, and
+ this guard models neither.
+ """
+ properties, utilities = _SHORTHANDS[utility]
+ shorthand = [
+ name for name in properties if re.search(rf"(?<![\w-]){re.escape(name)}:", body)
+ ] + [name for name in utilities if re.search(rf"(?<![\w-])@?{re.escape(name)}-\S", body)]
+ if shorthand:
+ # Unreadable rather than absent: the shorthand renders, and falling back to the base
+ # rule or reporting the longhand would both describe something that does not.
+ return None
+ values = _stated_units(body, utility, prop, spacing)
+ if not values:
+ return ""
+ if len(values) > 1 or values[0] is None:
+ return None
+ return values[0]
+
+
+def _stated_units(body: str, utility: str, prop: str, spacing: float) -> list[float | None]:
+ """Every value this rule states for one measure, in spacing units.
+
+ EVERY one, because CSS resolves a repeated declaration to the last, and a first-match
+ search reports the first. `.sidebar-row-action-glyph` gaining a `size-20` after its
+ `size-6`, or the base action rule gaining an `@apply pr-20` after its `pr-1.5`, changes
+ what renders and left every floor here unmoved. The caller refuses anything but a single
+ readable answer rather than picking one, since which wins also depends on specificity and
+ on where Tailwind emits the utility, and this guard does not model either.
+
+ None marks a value it cannot read, which must not collapse into "not stated".
+ """
+ found: list[float | None] = []
+ for match in re.finditer(rf"(?<![\w-]){re.escape(utility)}-(\S+?)(?=[\s;]|$)", body):
+ raw = match.group(1)
+ found.append(float(raw) if re.fullmatch(r"\d+(?:\.\d+)?", raw) else None)
+ for match in re.finditer(rf"(?<![\w-]){re.escape(prop)}:\s*([^;]+);", body):
+ value = match.group(1).strip()
+ rem = re.fullmatch(r"([\d.]+)rem", value)
+ px = re.fullmatch(r"([\d.]+)px", value)
+ if rem:
+ found.append(float(rem.group(1)) / spacing)
+ elif px:
+ found.append(float(px.group(1)) / 16 / spacing)
+ elif value == "0":
+ found.append(0.0)
+ else:
+ found.append(None)
+ return found
+
+
+def _base_row_action_offset(live_css: str, spacing: float) -> float | None:
+ """The right edge `.sidebar-row-action` itself sets, in units, or None if unreadable.
+
+ Every action's position is measured from this. It is `right-0` today, so an assumed zero
+ was right by luck; and returning on the first `@apply right-*` ignored a later
+ `right: 5rem` in the same rule, which is what CSS would render, so the reader went on
+ saying zero while every action extended into the title.
+ """
+ body = _own_declarations(live_css, ".sidebar-row-action")
+ if body is None:
+ return None
+ measure = _sole_measure(body, "right", "right", spacing)
+ return None if measure == "" or not isinstance(measure, float) else measure
+
+
+def _row_action_offsets(live_css: str, base: float, spacing: float) -> dict[str, float | None]:
+ """Each `.sidebar-row-action.is-*` modifier, and the right edge it renders with.
+
+ Read from CSS rather than named here, so an action positioned by a modifier this file has
+ never heard of is refused instead of being recorded as flush right. A modifier that states
+ no edge leaves the base rule's in force, which is what CSS does, so it gets *base* rather
+ than zero. None means the rule states one this cannot resolve, and the caller refuses it.
+ """
+ return {
+ name: base
+ if (measure := _sole_measure(body, "right", "right", spacing)) == ""
+ else (measure if isinstance(measure, float) else None)
+ for name, body in _modifier_rules(live_css).items()
+ }
+
+
+def _row_action_left_paddings(
+ live_css: str, base: float, spacing: float
+) -> dict[str, float | None]:
+ """Each modifier, and the LEFT padding it renders with, in units.
+
+ The left padding is inside the button, so it is part of what a tap hits even though it
+ shows nothing, and `.sidebar-row-action.sidebar-touch-reveal` makes the button clickable
+ on a coarse pointer. The pin sets it to zero for that reason; the shared options button
+ keeps the base, which faces the pin rather than the title.
+ """
+ return {
+ name: base
+ if (measure := _sole_measure(body, "pl", "padding-left", spacing)) == ""
+ else (measure if isinstance(measure, float) else None)
+ for name, body in _modifier_rules(live_css).items()
+ }
+
+
+def _row_action_paddings(live_css: str, base: float, spacing: float) -> dict[str, float | None]:
+ """Each modifier, and the right padding it renders with, in units.
+
+ The base `pr-1.5` is not what every action gets: the container is justify-end, so its
+ right padding decides where the glyph sits, and `.is-unpin-action` overrides it to
+ `0.125rem` to close the gap to the options button. Applying the base to every action put
+ the pin's reach at 15 when it is 14, and that false floor rejected a sufficient `pr-14`.
+ """
+ return {
+ name: base
+ if (measure := _sole_measure(body, "pr", "padding-right", spacing)) == ""
+ else (measure if isinstance(measure, float) else None)
+ for name, body in _modifier_rules(live_css).items()
+ }
+
+
+def _labelled_actions(
+ source: str,
+ block: str,
+ variant: str,
+ offsets: dict[str, float | None],
+ paddings: dict[str, float | None],
+ left_paddings: dict[str, float | None],
+ base_padding: float,
+ base_left: float,
+ base_offset: float,
+ live_css: str,
+) -> dict[int, tuple[str, float]]:
+ """The row actions one variant renders: label -> whether it is the offset one.
+
+ A row's actions are not all shared: the pin sits inside `{variant === "recent" && (` or
+ its project counterpart, while the options button is outside both and renders on every
+ row. Counting them together and applying the total to both rows would make an action
+ added to one of them require room on the other, failing a change that is correct.
+
+ A gate is read as everything between `{variant === "x" && (` and the parenthesis that
+ closes it; a button outside every gate belongs to both rows.
+ """
+ gates = []
+ for match in re.finditer(r'\{\s*variant\s*===\s*"(\w+)"\s*&&\s*\(', block):
+ depth = 0
+ for index in range(match.end() - 1, len(block)):
+ if block[index] == "(":
+ depth += 1
+ elif block[index] == ")":
+ depth -= 1
+ if depth == 0:
+ gates.append((match.group(1), match.start(), index))
+ break
+ found = {}
+ shared = []
+ cursor = 0
+ for tag in _opening_jsx_tags(block, "<button"):
+ at = block.find(tag, cursor)
+ cursor = at + 1 if at != -1 else cursor
+ classes = _button_classes(source, tag, variant)
+ assert classes is not None, (
+ f"a button in renderChatSidebarItem carries classes this guard cannot read, so it "
+ f"cannot tell whether it is a row action or how far it reaches: {tag!r}"
+ )
+ # Whole tokens, both here and below. CSS matches a class name exactly, so a substring
+ # test answers a different question than the stylesheet does: `sidebar-row-action-glyph`
+ # contains `sidebar-row-action` and would enrol a button that no rule positions.
+ worn = classes.split()
+ if "sidebar-row-action" not in worn:
+ continue
+ owners = [name for name, start, stop in gates if start <= at <= stop]
+ if owners and variant not in owners:
+ continue
+ # Keyed by where the element sits, not by its label. Keying on aria-label dropped any
+ # action that names itself another way, `aria-labelledby` being the ordinary one, and
+ # dropping the offset pin took the row's reach down to a single glyph while the pin
+ # went on rendering. The label is identity for the message only.
+ labels = re.findall(r"aria-label=\{?([^\n]{0,60})", tag)
+ name = labels[0] if labels else f"<unlabelled at {at}>"
+ # Visible on touch, which is the whole affordance. An action that keeps its row-action
+ # class but loses `sidebar-touch-reveal` stays counted, so the gutter still looks
+ # right while the button is transparent and inert on a coarse pointer.
+ # A whole token for the same reason, and it matters more in this direction. A typo or
+ # a rename to something longer, `sidebar-touch-reveal-disabled` being the obvious one,
+ # satisfies a substring test while matching no rule: the CSS that reveals the action
+ # still exists, so every other check here stays green, and the button goes on being
+ # transparent and inert on a coarse pointer.
+ assert "sidebar-touch-reveal" in worn, (
+ f"the {name} action on the {variant} row no longer carries sidebar-touch-reveal, "
+ f"so it is invisible and inert on a coarse pointer however much room the row "
+ f"reserves for it (#7276). It carries {worn}"
+ )
+ # Nothing inline. Every number below comes from the class list and index.css, and an
+ # inline style outranks both: `style={{ right: "5rem" }}` or
+ # `style={{ paddingRight: "5rem" }}` on the action moves it into the title while the
+ # reach here is still computed from the rules it no longer obeys. The row carrier is
+ # already refused this for the same reason; the actions needed it too.
+ escape = _escapes_the_model(tag)
+ assert escape is None, (
+ f"the {name} action {escape}, which outranks the classes and the CSS rules this "
+ f"guard measures it by, so the reach it computes is not the reach that renders: "
+ f"{tag!r}"
+ )
+ # Where it sits, read from the stylesheet. A `right-*` utility or a modifier the CSS
+ # does not define is positioning this guard has not modelled, and recording it as
+ # flush right would understate the reach of an action that renders further in.
+ # Under any variant, not bare. `[@media(pointer:coarse)]:right-40` positions the action
+ # on exactly the path this test is about, and matching only the unqualified spelling
+ # let it through: the reach would then be taken from the CSS modifier, or from zero,
+ # while the action rendered far into the title on every touch device.
+ # `right-*` was the only positioning refused, and it is not the only one that moves
+ # the action. A transform is the clearest case: `-translate-x-20` slides the pin five
+ # rem toward the title with its `right` untouched, so the computed reach did not
+ # change and the contract passed. Anything else that shifts the box horizontally, or
+ # sets the same edge by another route, belongs here for the same reason: the reach is
+ # derived from `right` and `padding-right` alone, and a utility outside that model
+ # renders something this arithmetic does not describe.
+ # Padding utilities too. The reach below substitutes the padding read from index.css
+ # for every action, so `!pr-20` on the element replaces the number being used while
+ # the calculation goes on with the stylesheet's, and the glyph clears the gutter.
+ utility = [
+ token
+ for token in worn
+ # The importance marker around `right-*` too. `!right-40` and `md:!right-40`
+ # render further in than the stylesheet offset this guard substitutes, and the
+ # bare form was the only one matched, so they went through untouched.
+ if re.fullmatch(rf"(?:\S*:)?!?right-\S+?!?|{_MOVES_HORIZONTALLY}", token)
+ or re.fullmatch(r"(?:\S*:)?!?(?:p|px|pe|pr)-\S+", token)
+ ]
+ assert not utility, (
+ f"the {name} action is positioned with {utility}, which this guard does not model: "
+ f"it reads the row's action offsets from index.css, so state the offset there"
+ )
+ # Plain classes on the action, looked up the same way the row's are. Only `is-*` is
+ # resolved through the stylesheet below, and `_escapes_the_model` reads inline styles
+ # and utility tokens, so an ordinary class with `.pushed-action { right: 5rem }`
+ # behind it moved the pin with nothing here the wiser.
+ named = {
+ token.rpartition(":")[2].strip("!")
+ for token in worn
+ if re.fullmatch(r"(?:\S*:)?!?[a-z][\w-]*!?", token) and not token.startswith("is-")
+ }
+ moved_by = _classes_setting(
+ live_css, named - _MODELLED_ACTION_CLASSES, _DECLARES_RIGHT_EDGE
+ )
+ assert not moved_by, (
+ f"the {name} action carries {moved_by}, whose rules in index.css move its right "
+ f"edge or change its padding. The reach below is computed from the base rule and "
+ f"the is-* modifiers alone, so it would not describe where this action renders"
+ )
+ modifiers = [token for token in worn if token.startswith("is-")]
+ unknown = [token for token in modifiers if token not in offsets]
+ assert not unknown, (
+ f"the {name} action carries {unknown}, which index.css does not define for "
+ f".sidebar-row-action, so this guard cannot tell how far that action reaches"
+ )
+ # A modifier whose rule sets `right` in a spelling this cannot read is not the same
+ # as one that leaves it alone, and recording it as zero would lower the floor while
+ # the action rendered further in.
+ unreadable = [token for token in modifiers if offsets[token] is None]
+ assert not unreadable, (
+ f"the {name} action carries {unreadable}, whose right edge index.css states in a "
+ f"spelling this guard cannot read. It reads a bare rem value, so state the offset "
+ f"that way or teach this guard the other one"
+ )
+ if not owners:
+ shared.append(name)
+ # The padding this action actually gets, not the base rule's. A modifier may override
+ # it, and `is-unpin-action` does, so crediting every action with `pr-1.5` overstated
+ # the pin's reach by a whole spacing unit.
+ stated = [token for token in modifiers if token in paddings]
+ unreadable_padding = [token for token in stated if paddings[token] is None]
+ assert not unreadable_padding, (
+ f"the {name} action carries {unreadable_padding}, whose right padding index.css "
+ f"states in a spelling this guard cannot read. It reads a bare rem value or an "
+ f"@apply pr-N, so state it that way or teach this guard the other one"
+ )
+ # Last modifier wins is not assumed: more than one stating a padding is an order
+ # question this does not adjudicate, so it is refused rather than guessed.
+ assert len(stated) <= 1, (
+ f"the {name} action carries {stated}, more than one of which sets a right "
+ f"padding. Which one applies is a question of source order in index.css, and "
+ f"this guard does not adjudicate it: state the padding on one modifier"
+ )
+ # No modifier at all means the base rule is the whole answer.
+ padding = paddings[stated[0]] if stated else base_padding
+ # The left padding too, because the button's whole box is what a tap hits and
+ # `sidebar-touch-reveal` makes it clickable on a coarse pointer. Measuring only as far
+ # as the glyph left 8px of the project row's title under the pin, where a tap pinned
+ # the chat instead of opening it.
+ stated_left = [token for token in modifiers if token in left_paddings]
+ unreadable_left = [token for token in stated_left if left_paddings[token] is None]
+ assert not unreadable_left, (
+ f"the {name} action carries {unreadable_left}, whose left padding index.css states "
+ f"in a spelling this guard cannot read, so how far the button reaches is unknown"
+ )
+ assert len(stated_left) <= 1, (
+ f"the {name} action carries {stated_left}, more than one of which sets a left "
+ f"padding, and which applies is a source-order question this does not adjudicate"
+ )
+ left = left_paddings[stated_left[0]] if stated_left else base_left
+ # A modifier that states no edge leaves the base rule's in force, so that is the
+ # fallback, not zero.
+ shift = max((offsets[token] for token in modifiers), default = base_offset)
+ found[at] = (name, shift + padding + left)
+ # Both rows carry an action that no `variant === "..."` gate guards, and every assertion
+ # below is written about a row that has one. Without this the per-variant pins alone keep
+ # both maps non-empty, so deleting the shared options button, or letting it lose
+ # `sidebar-row-action`, leaves the floor and the reserve agreeing with each other while
+ # the action the gutter was widened for is no longer rendered at all. Structural on
+ # purpose: an earlier form of this file keyed actions on `aria-label`, and matching the
+ # English "Chat options" would fail the moment the row is translated.
+ assert shared, (
+ f"the {variant} row renders no ungated .sidebar-row-action: every action it has sits "
+ f'inside a `variant === "..."` gate. The shared action is what the gutter on both '
+ f"rows is sized for, so if it moved behind a gate say so here, and if it was removed "
+ f"the reserved room should shrink with it (#7276)"
+ )
+ return found
+
+
+def _opening_jsx_tags(source: str, marker: str) -> list[str]:
+ """Every `marker ... >` opening tag in `source`, braces balanced.
+
+ A `>` inside an attribute expression does not end the tag, so depth is tracked rather
+ than scanning to the first one.
+ """
+ tags, start = [], source.find(marker)
+ while start != -1:
+ depth = 0
+ for index in range(start, len(source)):
+ char = source[index]
+ if char == "{":
+ depth += 1
+ elif char == "}":
+ depth -= 1
+ elif char == ">" and depth == 0:
+ tags.append(source[start : index + 1])
+ break
+ start = source.find(marker, start + 1)
+ return tags
+
+
+def _operators(text: str) -> list[tuple[int, str]]:
+ """Positions of `?`, `:`, `&&` and `||` that are not inside a string or brackets.
+
+ Tailwind's own colons all sit inside a quoted class list or inside `[...]`, so depth and
+ quoting are the whole of it. `?.` and `??` are skipped: they are not this grammar.
+ """
+ found, depth, quoted, index = [], 0, False, 0
+ while index < len(text):
+ char = text[index]
+ if quoted:
+ if char == '"':
+ quoted = False
+ index += 1
+ continue
+ if char == '"':
+ quoted = True
+ elif char in "([{":
+ depth += 1
+ elif char in ")]}":
+ depth -= 1
+ elif depth == 0 and (text.startswith("&&", index) or text.startswith("||", index)):
+ found.append((index, text[index : index + 2]))
+ index += 2
+ continue
+ elif depth == 0 and char == "?" and text[index + 1 : index + 2] not in (".", "?"):
+ found.append((index, "?"))
+ elif depth == 0 and char == ":":
+ found.append((index, ":"))
+ index += 1
+ return found
+
+
+def _branches(argument: str) -> list[tuple[tuple[tuple[str, bool], ...], str]]:
+ """Every value one cn() argument can evaluate to, with the conditions that select it.
+
+ The conditions come back as (text, truth) so that two arguments branching on the SAME
+ expression cannot be combined into a state neither can be in. That matters here: the
+ row's touch gutters live in `showWorkSpinner ? undefined : "...pair..."` while the room
+ for the spinner case is stated in a different argument, also on `showWorkSpinner`. A
+ product that ignored the correlation would invent a row with neither.
+ """
+ text = argument.strip()
+ marks = _operators(text)
+ opened = next((index for index, (_, token) in enumerate(marks) if token == "?"), None)
+ if opened is not None:
+ nested, closed = 0, None
+ for index in range(opened + 1, len(marks)):
+ token = marks[index][1]
+ if token == "?":
+ nested += 1
+ elif token == ":":
+ if nested == 0:
+ closed = marks[index][0]
+ break
+ nested -= 1
+ assert closed is not None, f"unbalanced ternary in {argument!r}"
+ condition = " ".join(text[: marks[opened][0]].split())
+ taken = []
+ for part, truth in (
+ (text[marks[opened][0] + 1 : closed], True),
+ (text[closed + 1 :], False),
+ ):
+ taken += [
+ (((condition, truth),) + constraints, value)
+ for constraints, value in _branches(part)
+ ]
+ return taken
+ # `||` binds looser than `&&`, so it splits first: `a || b && "x"` is `a || (b && "x")`,
+ # and taking the last operator textually would read it as `(a || b) && "x"` and hand the
+ # classes to a row that renders none of them. Within one operator they are
+ # left-associative, so the last of those is the outermost: `a && b && "x"` is one
+ # condition `a && b` carrying one value. Keeping the head whole rather than splitting it
+ # is what lets an identical head elsewhere correlate with this one.
+ short = [mark for mark in marks if mark[1] == "||"] or [
+ mark for mark in marks if mark[1] == "&&"
+ ]
+ if short:
+ cut, token = short[-1]
+ head = " ".join(text[:cut].split())
+ tail = text[cut + 2 :].strip()
+ if token == "&&":
+ return [(((head, True),), tail), (((head, False),), "undefined")]
+ return [(((head, True),), head), (((head, False),), tail)]
+ return [((), text)]
+
+
+def _values_are_readable(argument: str) -> bool:
+ """True when every value `argument` can evaluate to is a string literal or `undefined`.
+
+ Conditions are not values: in `a && "x"` and `c ? "x" : undefined` only the operands that
+ can BECOME the class string matter, so `a` and `c` may be anything.
+ """
+ return all(
+ value.strip() in ("", "undefined") or re.fullmatch(r'"[^"]*"', value.strip())
+ for _, value in _branches(argument)
+ )
+
+
+def _tokens(value: str) -> list[str]:
+ """The classes a branch value contributes, in order. `undefined` contributes none."""
+ value = value.strip()
+ return value.strip('"').split() if re.fullmatch(r'"[^"]*"', value) else []
+
+
+# Utilities that move an element horizontally by a route this file does not model. The reach
+# arithmetic is `right` plus `padding-right` and nothing else, so any of these renders
+# something it does not describe. `translate-y` is deliberately absent: it moves the element
+# vertically and the production spinner uses it, so refusing it would fail a correct row.
+_MOVES_HORIZONTALLY = (
+ r"(?:\S*:)?(?:-?translate-x|-?translate-(?!y)|inset-x|inset|left|-?mr|-?me)-\S+"
+ r"|(?:\S*:)?transform"
+)
+
+
+# The two the reach model already reads in full, so they are not "unmodelled".
+_MODELLED_ACTION_CLASSES = {"sidebar-row-action", "sidebar-row-action-glyph"}
+
+_DECLARES_RIGHT_PADDING = (
+ r"(?<![\w-])padding(?:-right|-inline-end)?:|@apply[^;]*(?<![\w-])!?(?:p|px|pe|pr)-"
+)
+# What moves an action's right edge, as a stylesheet declaration rather than a utility token.
+_DECLARES_RIGHT_EDGE = (
+ _DECLARES_RIGHT_PADDING
+ + r"|(?<![\w-])(?:right|inset(?:-inline)?|left|transform|translate|margin(?:-right)?):"
+ + r"|@apply[^;]*(?<![\w-])!?(?:right|inset|inset-x|left|-?mr|-?me|-?translate-x)-"
+)
+
+
[email protected]_cache(maxsize = 4)
+def _css_rules(live_css: str) -> tuple[tuple[str, str], ...]:
+ """Every rule in the stylesheet once, as (selector list, own declarations).
+
+ Cached and shared. The per-class scan below re-read the whole file for every class it was
+ asked about, five times over, which took about six seconds on its own: more than the other
+ thirty-six tests in this file put together.
+ """
+ rules = []
+ for match in re.finditer(r"([^{}]*)\{", live_css):
+ body = _declarations_at(live_css, match.end() - 1)
+ if body is not None:
+ rules.append((match.group(1), body))
+ return tuple(rules)
+
+
+def _classes_setting(live_css: str, classes: set[str], declares: str) -> list[str]:
+ """Which of *classes* index.css gives a declaration matching *declares*.
+
+ The gutter and reach comparisons read utilities off the elements, so an ordinary project
+ class whose rule sets the same property replaces the number that renders while the
+ comparison carries on with the utility's. A coarse-pointer rule doing it with `!important`
+ is the worst case: the row still says `pr-16` and the rendered gutter is zero.
+ """
+ offenders = []
+ for name in sorted(classes):
+ mentions = re.compile(rf"\.{re.escape(name)}(?![\w-])")
+ for selectors, body in _css_rules(live_css):
+ if not mentions.search(selectors):
+ continue
+ # On the element that carries the class, not on a descendant of it.
+ # `.sidebar-nav-btn .decorative-child { padding-right: 0 }` styles the child and
+ # leaves the row's gutter alone; reading it as the row's own padding would refuse
+ # harmless descendant styling. The class has to appear in the LAST compound of
+ # some selector in the list, which is the element the rule targets.
+ if not any(
+ mentions.search(re.split(r"[\s>+~]+", one.strip())[-1])
+ for one in selectors.split(",")
+ if one.strip()
+ ):
+ continue
+ if re.search(declares, body):
+ offenders.append(name)
+ break
+ return offenders
+
+
+def _escapes_the_model(tag: str) -> str | None:
+ """Why *tag*'s position cannot be read from its classes and index.css, or None.
+
+ Every number this file computes comes from a class list and a stylesheet rule. Three
+ things beat both: an inline `style`, a spread that could supply one, and a utility that
+ moves the element by a route the `right` plus `padding-right` sum does not model.
+
+ One function because the drift was the actual defect. The carrier, the row actions, the
+ spinner's wrapper and the spinner itself each grew these checks separately and each ended
+ up with a different subset, so a rule added to one path kept being missing from the next.
+ """
+ if re.search(r"(?:^|[\s{])style=", tag):
+ return "sets an inline style"
+ if any(_spread_may_supply(tag, name) for name in ("className", "style")):
+ return "takes a spread that may supply a className or a style"
+ moved = re.search(_MOVES_HORIZONTALLY, tag)
+ return f"is moved by {moved.group(0)!r}" if moved else None
+
+
+def _touch_spinner_reach(block: str, spacing: float) -> tuple[str, float] | None:
+ """How far the working-row spinner reaches into the row on a coarse pointer, in units.
+
+ The row actions are not the only thing the title has to clear. A working row also renders
+ a spinner, anchored right and pushed clear of the actions on touch, and the gutter has to
+ hold both. Measuring only the actions let the touch gutter drop from the 78px the spinner
+ needs to the 64px the pin needs, with the spinner then over the title.
+
+ Read the way everything else here is: the offset off the element that carries it, the
+ width off the glyph inside it, and None for anything this cannot resolve.
+ """
+ # The ternary that mounts a <span>, whatever its condition is called. Matching the name
+ # here and correlating on the same literal elsewhere would let the two drift apart.
+ gate = next(
+ (
+ found
+ for found in re.finditer(r"\{\s*([A-Za-z_$][\w$]*)\s*\?\s*\(", block)
+ if re.match(r"\s*<span", block[found.end() :])
+ ),
+ None,
+ )
+ if not gate:
+ return None
+ depth, end = 0, None
+ for index in range(gate.end() - 1, len(block)):
+ if block[index] == "(":
+ depth += 1
+ elif block[index] == ")":
+ depth -= 1
+ if depth == 0:
+ end = index
+ break
+ if end is None:
+ return None
+ rendered = block[gate.end() : end]
+ # Nothing inline or unmodelled on the element that positions it, for the same reason the
+ # actions and the carrier refuse both: `style={{ right: "8rem" }}` outranks the coarse
+ # `right-16` this reads, and a transform moves the spinner without touching `right` at
+ # all, so the reach reported here would not be the reach that renders.
+ positioning = [tag for tag in _opening_jsx_tags(rendered, "<span") if "absolute" in tag]
+ # The glyph as well as the wrapper. A transform on the <Spinner> moves what the reader
+ # sees while the wrapper's `right-16` and the glyph's `size-3.5`, which is all this
+ # measures, stay exactly as they were.
+ for tag in positioning + _opening_jsx_tags(rendered, "<Spinner"):
+ if _escapes_the_model(tag):
+ return None
+ offsets = [
+ float(match.group(1))
+ for match in re.finditer(
+ r"\[@media\(pointer:coarse\)\]:right-(\d+(?:\.\d+)?)(?![\w.-])", rendered
+ )
+ ]
+ # The spinner's own width, by the one route this reads. Another width utility on the same
+ # element renders wider than `size-3.5` while the regex below goes on reporting 3.5, so
+ # any of them makes the measurement unreadable rather than merely different.
+ for tag in _opening_jsx_tags(rendered, "<Spinner"):
+ if re.search(r"(?<![\w-])!?(?:w|min-w|max-w|basis)-\S", tag):
+ return None
+ if len(re.findall(r"(?<![\w-])size-\d", tag)) > 1:
+ return None
+ widths = [
+ float(match.group(1))
+ for match in re.finditer(
+ r"<Spinner[^>]*?(?<![\w-])size-(\d+(?:\.\d+)?)(?![\w.-])", rendered, re.S
+ )
+ ]
+ if len(offsets) != 1 or len(widths) != 1:
+ return None
+ # The gate's own condition is returned with the measurement, because the caller has to
+ # correlate it with the builder's branches. Naming `showWorkSpinner` there and reading it
+ # here would let the two drift: spell the gate `Boolean(showWorkSpinner)` in both places
+ # and a caller keyed on the literal name finds no spinner rendering and skips them all.
+ return gate.group(1), offsets[0] + widths[0]
+
+
+def _rendered_class_lists(arguments: list[str]) -> list[list[str]]:
+ """Every class list the builder can produce, in builder order, one per live branch.
+
+ Combinations that would need one condition to hold two truths at once are dropped, not
+ checked: they are not rows anyone can render.
+ """
+ return [classes for _, classes in _rendered_with_conditions(arguments)]
+
+
+def _rendered_with_conditions(arguments: list[str]) -> list[tuple[dict[str, bool], list[str]]]:
+ """As above, but keeping which conditions each rendering needed.
+
+ The conditions are what tie a rendering to the rest of the row. The spinner is gated on
+ the same flag as the row's widest gutter, and without them a check can only ask what SOME
+ rendering reserves, not what the rendering that shows the spinner reserves.
+ """
+ lists: list[tuple[dict[str, bool], list[str]]] = [({}, [])]
+ for argument in arguments:
+ grown = []
+ for constraints, classes in lists:
+ for extra, value in _branches(argument):
+ merged = dict(constraints)
+ if any(merged.setdefault(name, truth) != truth for name, truth in extra):
+ continue
+ grown.append((merged, classes + _tokens(value)))
+ lists = grown
+ return lists
+
+
+def _cn_arguments(body: str) -> list[str]:
+ """`body` split on top-level commas, ignoring those inside brackets or strings."""
+ parts, depth, quoted, current = [], 0, False, []
+ for char in body:
+ if quoted:
+ current.append(char)
+ if char == '"':
+ quoted = False
+ continue
+ if char == '"':
+ quoted = True
+ elif char in "([{":
+ depth += 1
+ elif char in ")]}":
+ depth -= 1
+ elif char == "," and depth == 0:
+ parts.append("".join(current))
+ current = []
+ continue
+ current.append(char)
+ if current:
+ parts.append("".join(current))
+ return [part for part in parts if part.strip()]
+
+
def test_chat_sidebar_row_actions_visible_on_coarse_pointers():
"""unslothai/unsloth#7276: Recents chat kebab must be tappable on iPad."""
sidebar_source = APP_SIDEBAR.read_text(encoding = "utf-8")
@@ -860,7 +1715,488 @@ def test_chat_sidebar_row_actions_visible_on_coarse_pointers():
block = sidebar_source.split("function renderChatSidebarItem", 1)[1].split("\n function ", 1)[
0
]
- assert "[@media(pointer:coarse)]:pr-10" in block
+ # The split above bounds the block at the next top-level function, and a nested one inside
+ # renderChatSidebarItem ends it early. When #11373 added one, the block shrank to the
+ # signature and a comment, and every assertion below started reading an empty room. A
+ # truncated block must fail as a stale guard, not as a missing affordance.
+ assert len(block) > 2000, (
+ f"renderChatSidebarItem now yields only {len(block)} characters, so this guard is "
+ f"reading a fragment rather than the row. Widen the bound before trusting anything "
+ f"it says about the row's classes"
+ )
+ # Reserved room for the action on touch, where there is no hover to make it appear. The
+ # width is not a constant to pin: it was pr-10, and became pr-14 for project rows and
+ # pr-16 for recents when the row gained an action. What does not move is that the row
+ # already states how much room that action needs, in the padding it applies on HOVER. So
+ # the claim is that a coarse pointer gets at least the same gutter, whatever it is.
+ #
+ # Per VARIANT, not once for the block. The two rows carry their own paddings, so a single
+ # search over the whole function is satisfied by the project row on its own and would stay
+ # green while recents lost theirs, which is the half of #7276 that was actually reported.
+ #
+ # An earlier version of this worked out which padding WINS: last in cn order, across
+ # arguments, with conditional arguments applying only to their own branch and an
+ # important utility beating an ordinary one written after it. Every rule it gained was
+ # right and the next one was still missing, because that question is tailwind-merge plus
+ # the cascade and a test file should not hold a second copy of either.
+ #
+ # So it does not decide. Each variant's row states one hover gutter and one coarse
+ # padding, both written plainly, and the coarse one must be at least the hover one.
+ # Anything else, a second coarse padding anywhere in the row's own cn(), a variant
+ # qualifier, an importance marker, is refused as something this guard will not
+ # adjudicate. That is stricter than the framework and it is stricter LOUDLY, which is
+ # the half that matters: it cannot quietly approve a gutter nobody checked.
+ # The row's own builder, by name, and the classes are read only from inside it. Searching
+ # the whole function let the same verified pairs be moved to any other cn() call and
+ # still satisfy this, while the buttons that render carried no gutter at all.
+ # Comments out of the way BEFORE anything is located, not after. An old builder left
+ # inside `/* ... */` sits earlier in the function than the live one, so a search over the
+ # raw text selected the dead declaration and the gutter analysis then described classes
+ # nothing renders, while the carrier check below saw the live `buttonClass` and agreed.
+ # `{/* ... */}` is how a prop is commented out in JSX, and it is the spelling that would
+ # be used here, so a stripper that only knew `//` left a disabled className reading as a
+ # live one. Block form first, then line form.
+ applied = re.sub(r"\{?\s*/\*.*?\*/\s*\}?", " ", block, flags = re.S)
+ applied = "\n".join(re.sub(r"(?<!:)//.*$", "", line) for line in applied.splitlines())
+ builder = re.search(r"const buttonClass = cn\(", applied)
+ assert builder, (
+ "renderChatSidebarItem no longer builds its row classes in a `const buttonClass = "
+ "cn(...)`, so this guard cannot tell which classes reach the row button"
+ )
+ depth, builder_end = 0, None
+ for index in range(builder.end() - 1, len(applied)):
+ if applied[index] == "(":
+ depth += 1
+ elif applied[index] == ")":
+ depth -= 1
+ if depth == 0:
+ builder_end = index
+ break
+ assert builder_end is not None, "unbalanced `const buttonClass = cn(` in the sidebar"
+ # On the row button itself, not merely somewhere in the function. The row also renders an
+ # inline rename input and a pin, and handing buttonClass to one of those while the button
+ # went without would leave every padding check below describing classes that reach nothing
+ # the gutters are measured against.
+ carriers = [
+ tag
+ for tag in _opening_jsx_tags(applied, "<SidebarMenuButton")
+ if re.search(r"(?:^|[\s{])className=\{buttonClass\}", tag)
+ ]
+ # An inline style outranks every Tailwind utility, and none of them is read here.
+ # `style={{ paddingRight: 0 }}` on the carrier puts the always-visible touch actions
+ # straight back over the title while every gutter assertion below stays green, because
+ # only buttonClass is analysed.
+ # A spread counts wherever it sits. Ordering only settles `className`, where the explicit
+ # attribute beats a spread written before it; it settles nothing about `style`, which no
+ # attribute here declares, so `{...rowProps}` with a `style.paddingRight` of 0 overrides
+ # every pr-N gutter below from either side of the className.
+ escaped = [(tag, _escapes_the_model(tag)) for tag in carriers]
+ offending = [(tag, why) for tag, why in escaped if why]
+ assert not offending, (
+ f"a row carrier {offending[0][1] if offending else ''}, which outranks the pr-N "
+ f"gutters this guard compares, so the room it computes is not the room that renders: "
+ f"{[tag for tag, _ in offending]!r}"
+ )
+ assert carriers, (
+ "no <SidebarMenuButton> in renderChatSidebarItem receives className={buttonClass}, so "
+ "the classes checked below do not reach the row button and say nothing about the row "
+ "that renders"
+ )
+ # Only a spread written AFTER the class, because JSX applies attributes in order and the
+ # last write wins: `<SidebarMenuButton {...rowProps} className={buttonClass}>` ends with
+ # the explicit one whatever the spread holds. Refusing that shape would fail a refactor
+ # that forwards unrelated props, which stops correct work rather than catching anything.
+ spreading = [
+ tag
+ for tag in carriers
+ if any(
+ match.start() > re.search(r"(?:^|[\s{])className=\{buttonClass\}", tag).start()
+ for match in re.finditer(r"\{\s*\.\.\.", tag)
+ )
+ ]
+ assert not spreading, (
+ f"the row button spreads props after className={{buttonClass}}, so whether those "
+ f"classes survive depends on what the spread holds, which this guard cannot resolve: "
+ f"{spreading!r}"
+ )
+ # Comments first: they hold commas and prose, and splitting arguments around them turns
+ # a sentence into an unreadable "value".
+ row_classes = "\n".join(
+ re.sub(r"(?<!:)//.*$", "", line)
+ for line in applied[builder.end() : builder_end].splitlines()
+ )
+ # Every value the builder contributes has to be readable. An identifier holding a class
+ # string is invisible to a scan over quoted literals, so `cn(..., coarseOverride)` would
+ # make pr-0 effective while this guard went on reporting the gutter above it. Conditions
+ # may be anything; it is the VALUES that have to be literals or undefined.
+ unresolved = [
+ argument for argument in _cn_arguments(row_classes) if not _values_are_readable(argument)
+ ]
+ assert not unresolved, (
+ f"buttonClass is built from values this guard cannot read: {unresolved}. A class "
+ f"string held in an identifier can override the row's gutters without appearing "
+ f"here, so keep the row's classes as literals"
+ )
+
+ # Every class the builder can contribute, whichever way its conditions fall. Padding is
+ # read off these branches rather than off the literals, because a literal found anywhere
+ # in the builder says nothing about the rows that do not take it: moving the verified
+ # pair into `showWorkSpinner ? "...pair..." : undefined` leaves every ordinary row with
+ # no gutter at all while a scan over literals still finds it.
+ live_css = re.sub(r"/\*.*?\*/", " ", css_source, flags = re.S)
+ spacing = _spacing_rem(live_css)
+ assert spacing is not None, (
+ "index.css does not state one readable --spacing, so this guard cannot convert the "
+ "pin's fixed rem offset and padding into the pr-N units the row's gutters are in, and "
+ "the two sides of every comparison below would be in different scales"
+ )
+ rendered = [
+ (constraints, [_as_spacing_units(cls, spacing) for cls in rendering])
+ for constraints, rendering in _rendered_with_conditions(_cn_arguments(row_classes))
+ ]
+ renderings = [classes for _, classes in rendered]
+ every_class = [cls for rendering in renderings for cls in rendering]
+ # Refused across the WHOLE builder, not just the row's own literal. What follows compares
+ # pr-N numbers and takes the last one to win, which is tailwind-merge's answer only while
+ # nothing here changes the same edge by another route or jumps the queue with `!`. A
+ # single `"!pr-0"` argument beats every coarse gutter below it and carries no marker that
+ # a search for coarse-pointer strings would find.
+ marked = [
+ cls for cls in every_class if re.fullmatch(r"(?:\S*:)?!p\w*-\S+|(?:\S*:)?p\w*-\S+!", cls)
+ ]
+ assert not marked, (
+ f"buttonClass sets padding with an importance marker: {marked}. `!` beats an "
+ f"ordinary utility written after it, so which gutter the row ends up with stops "
+ f"being a question of order, and this guard will not adjudicate it"
+ )
+ shorthand = [cls for cls in every_class if re.fullmatch(r"(?:\S*:)?(?:p|px|pe)-\S+", cls)]
+ assert not shorthand, (
+ f"buttonClass sets padding with a shorthand that also moves the right edge: "
+ f"{shorthand}. It overrides the pr-N gutters this guard compares, so state the "
+ f"row's padding with pr-N alone"
+ )
+ arbitrary = [
+ cls
+ for cls in every_class
+ if re.search(r"\[padding(?:-right)?:[^\]]*\]|(?<![\w-])p[rxe]?-\[[^\]]*\]", cls)
+ ]
+ assert not arbitrary, (
+ f"buttonClass sets its right padding through an arbitrary value: {arbitrary}. This "
+ f"guard compares pr-N gutters and will not work out how that interacts with them: "
+ f"state the touch padding as a pr-N utility"
+ )
+
+ # Everything below compares pr-N numbers, and tailwind-merge drops an earlier `pr-` for a
+ # later one whatever the later one's value is. `pr-px` is a real utility worth one pixel:
+ # it replaces the checked gutter and, being unnumbered, was read by nothing here. So any
+ # right padding the builder can contribute has to be a number this guard can compare.
+ unnumbered = [
+ cls
+ for cls in every_class
+ if re.fullmatch(r"(?:\S*:)?pr-\S+", cls)
+ and not re.fullmatch(r"(?:\S*:)?pr-\d+(?:\.\d+)?", cls)
+ ]
+ assert not unnumbered, (
+ f"buttonClass states a right padding this guard cannot compare: {unnumbered}. It "
+ f"still replaces the numeric gutters through tailwind-merge, so the comparison below "
+ f"would go on reporting a value that no longer renders"
+ )
+
+ # And under a qualifier it reads. Being numeric is not enough: the three shapes below are
+ # the ones the comparison looks at, and a padding under any other variant was matched by
+ # none of them and so left out of the answer entirely while still rendering.
+ # `focus:[@media(pointer:coarse)]:pr-0` is the case, effective on a focused touch row and
+ # invisible here. Refusing it is the same rule already applied to importance markers and
+ # arbitrary values: this guard does not adjudicate what it cannot read.
+ readable_padding = re.compile(
+ r"pr-\d+(?:\.\d+)?"
+ r"|\[@media\(pointer:coarse\)\]:pr-\d+(?:\.\d+)?"
+ r"|[\w:\[\]().,=^-]*/(?:project-chat-item|recent-item):pr-\d+(?:\.\d+)?"
+ )
+ unqualified = sorted(
+ {
+ cls
+ for cls in every_class
+ if re.search(r"(?:^|:)pr-\d", cls) and not readable_padding.fullmatch(cls)
+ }
+ )
+ assert not unqualified, (
+ f"buttonClass states a right padding under a qualifier this guard does not read: "
+ f"{unqualified}. It renders in the state that qualifier names, and the comparison "
+ f"below reports the gutters it does read, so the row would be credited with padding "
+ f"that state does not have"
+ )
+
+ coarse_prefix = r"\[@media\(pointer:coarse\)\]:"
+ # And no plain class on the row quietly sets the same edge. Everything below compares
+ # `pr-N` utilities; a project class whose rule states a right padding replaces what
+ # renders without appearing in that comparison at all.
+ named = {
+ token.rpartition(":")[2].strip("!")
+ for token in every_class
+ if re.fullmatch(r"(?:\S*:)?!?[a-z][\w-]*!?", token)
+ }
+ gutter_classes = _classes_setting(live_css, named, _DECLARES_RIGHT_PADDING)
+ assert not gutter_classes, (
+ f"the row carries {gutter_classes}, whose rules in index.css set a right padding of "
+ f"their own. That is the gutter that renders, and the comparison below reads the pr-N "
+ f"utilities instead, so it would credit the row with room it does not have"
+ )
+
+ # The spinner too, on the renderings that show it. Everything above measures the row's
+ # actions, and a working row also renders a spinner that the title has to clear: it sits
+ # further in than the pin on touch, which is why the row reserves 78px there and not the
+ # 64 the actions alone would need. Without this the touch gutter could drop to the
+ # actions' floor with the spinner left over the title, and every check above would pass.
+ spinner = _touch_spinner_reach(applied, spacing)
+ assert spinner is not None, (
+ "renderChatSidebarItem no longer states the working-row spinner's coarse offset and "
+ "size in a form this guard can read, so it cannot tell how much room a working row "
+ "has to reserve beyond its actions"
+ )
+ spinner_gate, spinner_reach = spinner
+ # Correlated, or refused. Skipping renderings whose constraints do not mention the gate
+ # treats "this is not a working row" and "this guard could not tell" as the same answer,
+ # and the second one is how the whole check quietly stops running.
+ showing = [
+ (constraints, rendering)
+ for constraints, rendering in rendered
+ if constraints.get(spinner_gate)
+ ]
+ assert showing, (
+ f"no rendering of the row's classes is conditioned on {spinner_gate!r}, the same "
+ f"condition that gates the spinner, so this guard cannot tell which rows show one "
+ f"and would check the spinner's gutter on none of them"
+ )
+ for constraints, rendering in showing:
+ touch = [
+ float(match.group(1))
+ for match in (
+ re.fullmatch(coarse_prefix + r"pr-(\d+(?:\.\d+)?)", cls) for cls in rendering
+ )
+ if match
+ ]
+ plain = [
+ float(match.group(1))
+ for match in (re.fullmatch(r"pr-(\d+(?:\.\d+)?)", cls) for cls in rendering)
+ if match
+ ]
+ reserved = touch[-1] if touch else (plain[-1] if plain else None)
+ assert reserved is not None and reserved >= spinner_reach, (
+ f"a working row reserves {reserved} on a coarse pointer, under the "
+ f"{spinner_reach} its spinner reaches. The spinner is always visible there, so "
+ f"it would sit over the title (#7276)"
+ )
+
+ variants = ("project-chat-item", "recent-item")
+ # Every rendering is some row, and a rendering that claims no gutter at all was being
+ # skipped as "not this variant" by each variant's loop in turn, so wrapping both variants'
+ # gutters in the same condition left ordinary rows with no touch padding and nothing
+ # checking them. A row is identified by the gutter it claims, so a row that claims none
+ # cannot be identified, and that is the thing to refuse rather than to skip.
+ for rendering in renderings:
+ if not any(
+ re.fullmatch(rf"\S*/{re.escape(name)}:pr-\d+(?:\.\d+)?", cls)
+ for name in variants
+ for cls in rendering
+ ):
+ raise AssertionError(
+ f"buttonClass can render a row that states no action gutter for either "
+ f"variant: {rendering}. The row's actions are always visible on touch, so a "
+ f"row that reserves nothing puts them over the title (#7276). If this branch "
+ f"really renders no action, give it a gutter of its own rather than leaving "
+ f"it unidentifiable"
+ )
+
+ # A floor under both sides, because the comparison below is relative and reducing the two
+ # together satisfies it while reserving nothing usable: pr-0.5 against pr-0.5 passes. The
+ # floor is what the row's actions occupy, so it has to count them rather than assume one.
+ # A row carries a pin and an options button, and reserving a single glyph for the two of
+ # them puts the pin back over the title, which is the regression this exists to stop.
+ # Over CSS with its comments removed, for the same reason the TSX reads are: an old rule
+ # left inside `/* ... */` sits before the live one and is the one a search finds, so the
+ # floor would be measured from a glyph nothing renders.
+ glyph_rule = _own_declarations(live_css, ".sidebar-row-action-glyph")
+ assert glyph_rule is not None, (
+ "index.css no longer has a .sidebar-row-action-glyph rule, so this guard cannot tell "
+ "how much room one action needs"
+ )
+ # Any other route to the glyph's width is refused. `size-*` and `width` are the two this
+ # reads; a `min-width`, `max-width`, `inline-size` or an `@apply w-*` in the same rule
+ # widens the box while this goes on reporting the original size.
+ other_width = re.search(
+ r"(?<![\w-])(?:min-width|max-width|inline-size|block-size):"
+ r"|@apply[^;]*(?<![\w-])(?:w|min-w|max-w|basis)-",
+ glyph_rule,
+ )
+ assert not other_width, (
+ f"the glyph's rule sets its width through {other_width.group(0)!r} as well as the "
+ f"size this guard reads, so the box that renders is wider than the one it measures"
+ )
+ # And at each glyph that renders, not only in the shared rule. The floor is one number
+ # taken from `.sidebar-row-action-glyph`, so an instance carrying `min-w-20`, or an inline
+ # width, is wider than every action is credited with while this goes on reporting size-6.
+ for tag in _opening_jsx_tags(applied, "<span"):
+ if not re.search(r"(?<![\w-])sidebar-row-action-glyph(?![\w-])", tag):
+ continue
+ escape = _escapes_the_model(tag)
+ assert escape is None, (
+ f"a row action's glyph {escape}, so the box that renders is not the one the floor "
+ f"below is measured from: {tag!r}"
+ )
+ widened = re.findall(r"(?<![\w-])!?(?:w|min-w|max-w|basis|size)-\S+", tag)
+ assert not widened, (
+ f"a row action's glyph sets its own width with {widened}, overriding the shared "
+ f"rule this guard measures, so that action reaches further than the floor says"
+ )
+
+ sizes = _stated_units(glyph_rule, "size", "width", spacing)
+ assert len(sizes) == 1 and sizes[0] is not None, (
+ f"the glyph's size is not one value this guard can read: {sizes}. A second one later "
+ f"in the rule is what renders, and every floor below would go on being measured from "
+ f"the first, so state it once in a spelling this reads"
+ )
+ # Read per variant, because each variant's own actions decide its floor: an action added to
+ # one row only would otherwise require the other to reserve room for something it does not
+ # render, and this guard would fail a correct change.
+ glyph_size = sizes[0]
+ # The actions do not sit side by side and counting them assumed they did. They are
+ # absolutely positioned and one is pushed clear of the other, so what the row has to
+ # reserve is how far the furthest one reaches, not how many there are. Each action's
+ # offset comes from `_row_action_offsets`, read out of the stylesheet.
+ # To the far edge of the GLYPH, which is where the ink stops, but through the padding
+ # that positions it. The container is justify-end with its own pr, so the glyph's right
+ # edge sits that far inside the container's, and its left edge is offset + pr + size.
+ # Leaving the pr out under-measured every row by 1.5, which is how the project row's
+ # pr-14 passed while its pin reached 15.
+ base_rule = _own_declarations(live_css, ".sidebar-row-action")
+ assert base_rule is not None, (
+ "index.css no longer has a .sidebar-row-action rule, so this guard cannot tell where "
+ "inside its container the glyph sits"
+ )
+ # Through _sole_measure, so the shorthand refusal reaches this rule too. Reading the
+ # longhand directly here was how `padding: 0 5rem` in the base rule went unnoticed.
+ base_padding = _sole_measure(base_rule, "pr", "padding-right", spacing)
+ assert isinstance(base_padding, float), (
+ f"the base action's right padding is not one value this guard can read "
+ f"({base_padding!r}). A later declaration, or a shorthand that contains it, is what "
+ f"renders, and the shared action would reach further into the title while the floor "
+ f"stayed put"
+ )
+ inner_padding = base_padding
+ # The container's `pl` IS part of the reach, and for a while this said otherwise. The
+ # argument then was that `pr` decides where the glyph sits while `pl` only extends a
+ # transparent box, so only the ink counted. That is right about what is SEEN and wrong
+ # about what is HIT: `.sidebar-row-action.sidebar-touch-reveal` is `pointer-events-auto`,
+ # so the whole button takes taps, padding included, and #7276 is about the action
+ # intercepting the title. The pin's own `padding-left: 0` is what keeps the two answers
+ # the same size now, so measuring the full box costs the rows nothing.
+ base_left_measure = _sole_measure(base_rule, "pl", "padding-left", spacing)
+ assert isinstance(base_left_measure, float), (
+ f"the base action's left padding is not one value this guard can read "
+ f"({base_left_measure!r}). It sits inside the button, so a tap lands on it, and the "
+ f"reach below cannot be computed without it"
+ )
+ base_left = base_left_measure
+ base_offset = _base_row_action_offset(live_css, spacing)
+ assert base_offset is not None, (
+ "index.css no longer states a right edge for .sidebar-row-action in a spelling this "
+ "guard can read. Every action's position is measured from it, so reading it as flush "
+ "would understate every reach below by however far the base rule moves them"
+ )
+ offsets = _row_action_offsets(live_css, base_offset, spacing)
+ actions = {
+ name: _labelled_actions(
+ sidebar_source,
+ applied,
+ name,
+ offsets,
+ _row_action_paddings(live_css, inner_padding, spacing),
+ _row_action_left_paddings(live_css, base_left, spacing),
+ inner_padding,
+ base_left,
+ base_offset,
+ live_css,
+ )
+ for name in ("project", "recent")
+ }
+ assert all(actions.values()), (
+ f"no labelled row action left for one of the variants, so this guard cannot tell how "
+ f"much room that row has to reserve: "
+ f"{ {name: len(found) for name, found in actions.items()} }"
+ )
+ reach = {
+ name: max(edge + glyph_size for _, edge in found.values())
+ for name, found in actions.items()
+ }
+ floors = {"project-chat-item": reach["project"], "recent-item": reach["recent"]}
+
+ for variant in variants:
+ # Any qualified gutter for this variant, not the hover one alone: hover, an open menu
+ # and keyboard focus each state how much room the row's action needs, and each is a
+ # state a coarse pointer is permanently in, because there the action is always shown.
+ qualified = re.compile(rf"\S*/{re.escape(variant)}:pr-(\d+(?:\.\d+)?)$")
+ assert any(qualified.fullmatch(cls) for cls in every_class), (
+ f"no {variant} row left that widens its padding to make room for the action, so "
+ f"this guard can no longer tell whether the touch case is covered"
+ )
+ for rendering in renderings:
+ claimed = [
+ float(match.group(1))
+ for match in (qualified.fullmatch(cls) for cls in rendering)
+ if match
+ ]
+ # A rendering that states no gutter for this variant is not this variant's row.
+ if not claimed:
+ continue
+ touch = [
+ float(match.group(1))
+ for match in (
+ re.fullmatch(coarse_prefix + r"pr-(\d+(?:\.\d+)?)", cls) for cls in rendering
+ )
+ if match
+ ]
+ plain = [
+ float(match.group(1))
+ for match in (re.fullmatch(r"pr-(\d+(?:\.\d+)?)", cls) for cls in rendering)
+ if match
+ ]
+ # Last one wins: same variant, so tailwind-merge keeps the later utility, and a
+ # coarse-pointer utility outranks an unqualified one whatever the order, since
+ # Tailwind emits variants after base and a media query adds no specificity.
+ reserved = touch[-1] if touch else (plain[-1] if plain else None)
+ needed = max(claimed)
+ # Both sides reduced together satisfies the comparison below and reserves nothing
+ # usable, which is the state this test was written against: the action keeps its
+ # width whatever the row says, so a row that claims less than one action's worth
+ # has not been fixed, it has stopped claiming. The gutter's exact size is still
+ # not pinned here, only that it holds at least one action.
+ # EVERY state that claims a gutter, not the largest of them. Each qualified class
+ # names a state in which the action is visible, and in that state the row reserves
+ # exactly that gutter, so one of them dropping to pr-0 removes the reservation
+ # there while `max` goes on reporting a sibling's 16. An open menu on a coarse
+ # pointer is such a state.
+ assert min(claimed) >= floors[variant], (
+ f"a {variant} row states an action gutter of {min(claimed)} among {claimed}, "
+ f"under the {floors[variant]} its furthest action reaches. The state that "
+ f"claims it reserves nothing, whatever the others claim, and the action is "
+ f"visible in it (#7276)"
+ )
+ assert needed >= floors[variant], (
+ f"a {variant} row states its action gutter as {claimed}, under the "
+ f"{floors[variant]} that its furthest action reaches "
+ f"at .sidebar-row-action-glyph's size. Nothing then reserves room for actions "
+ f"that still have their width, and the comparison below is satisfied by two "
+ f"equally small numbers, which is the overlap this test exists to catch "
+ f"rather than a row that has been fixed (#7276)"
+ )
+ assert reserved is not None and reserved >= needed, (
+ f"a {variant} row reserves less room on a coarse pointer than it says its "
+ f"action needs: {reserved} against {needed}, on the row that renders as "
+ f"{rendering}. The action is always visible on touch, so it needs at least "
+ f"the room the hover, open-menu and focus cases already say it needs, or it "
+ f"sits over the title (#7276)"
+ )
assert "sidebar-touch-reveal" in block
# Coarse-pointer visibility must come after .sidebar-row-action { opacity-0 }.
coarse_idx = css_source.index("@media (pointer: coarse)")