Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: stop dropping the page text after a menu with no closing tag (#13489)
Nilay530c0da4bc02
diff --git a/studio/backend/core/inference/_html_to_md.py b/studio/backend/core/inference/_html_to_md.pyindex 948bd49a5ff..00171b02968 100644--- a/studio/backend/core/inference/_html_to_md.py+++ b/studio/backend/core/inference/_html_to_md.py@@ -128,9 +128,14 @@ _P_CLOSING_TAGS = frozenset("article","aside","blockquote",+ "center",+ "dd","details",+ "dialog",+ "dir","div","dl",+ "dt","fieldset","figcaption","figure",@@ -145,13 +150,17 @@ _P_CLOSING_TAGS = frozenset("header","hgroup","hr",+ "li",+ "listing","main","menu","nav","ol","p","pre",+ "search","section",+ "summary","table","ul",}@@ -202,16 +211,158 @@ _BLOCK_TAGS = frozenset(})_HEADING_TAGS = frozenset({"h1", "h2", "h3", "h4", "h5", "h6"})-# half the 16K fetch result: repeated span cells must leave room for the source text after the table++# end tags pop through descendants only when their target is in the matching HTML parser scope+_SKIP_RECOVERY_END_TAGS = (+ frozenset(+ {+ "address",+ "applet",+ "article",+ "aside",+ "blockquote",+ "button",+ "caption",+ "center",+ "dd",+ "details",+ "dialog",+ "dir",+ "div",+ "dl",+ "dt",+ "fieldset",+ "figcaption",+ "figure",+ "footer",+ "header",+ "hgroup",+ "li",+ "listing",+ "main",+ "marquee",+ "menu",+ "nav",+ "object",+ "ol",+ "p",+ "pre",+ "search",+ "section",+ "select",+ "summary",+ "table",+ "tbody",+ "td",+ "tfoot",+ "th",+ "thead",+ "tr",+ "ul",+ }+ )+ | _HEADING_TAGS+)+_GENERIC_END_SKIP_TAGS = frozenset({"datalist"})+_SPECIAL_HTML_TAGS = _SKIP_RECOVERY_END_TAGS | frozenset(+ {+ "body",+ "colgroup",+ "form",+ "frameset",+ "head",+ "html",+ "iframe",+ "noembed",+ "noframes",+ "noscript",+ "plaintext",+ "script",+ "style",+ "template",+ "title",+ "xmp",+ }+)+_SCOPE_BARRIERS = frozenset(+ {"applet", "caption", "html", "marquee", "object", "select", "table", "td", "template", "th"}+)+_SVG_SCOPE_BARRIERS = frozenset({"foreignobject", "desc", "title"})+_MATHML_SCOPE_BARRIERS = frozenset({"mi", "mo", "mn", "ms", "mtext", "annotation-xml"})+_MATHML_TEXT_INTEGRATION_POINTS = frozenset({"mi", "mo", "mn", "ms", "mtext"})+_FOREIGN_HTML_BREAKOUT_START_TAGS = frozenset(+ {+ "b",+ "big",+ "blockquote",+ "body",+ "br",+ "center",+ "code",+ "dd",+ "div",+ "dl",+ "dt",+ "em",+ "embed",+ "h1",+ "h2",+ "h3",+ "h4",+ "h5",+ "h6",+ "head",+ "hr",+ "i",+ "img",+ "li",+ "listing",+ "menu",+ "meta",+ "nobr",+ "ol",+ "p",+ "pre",+ "ruby",+ "s",+ "small",+ "span",+ "strike",+ "strong",+ "sub",+ "sup",+ "table",+ "tt",+ "u",+ "ul",+ "var",+ }+)+_LIST_ITEM_SCOPE_BARRIERS = _SCOPE_BARRIERS | {"ol", "ul"}+_BUTTON_SCOPE_BARRIERS = _SCOPE_BARRIERS | {"button"}+_IMPLICIT_CLOSE_BARRIERS = {+ tag: _CLOSE_BARRIERS.get(tag, frozenset())+ | (_BUTTON_SCOPE_BARRIERS if tag in _P_CLOSING_TAGS else frozenset())+ for tag in _CLOSE_BARRIERS.keys() | _P_CLOSING_TAGS+}+_TABLE_SCOPE_BARRIERS = frozenset({"html", "table", "template"})+_TABLE_END_TAGS = frozenset({"caption", "table", "tbody", "td", "tfoot", "th", "thead", "tr"})+_TABLE_CONTEXT_END_TAGS = _TABLE_END_TAGS - {"table"}+_TABLE_ONLY_START_TAGS = _TABLE_CONTEXT_END_TAGS | {"col", "colgroup"}+_TABLE_CELL_TAGS = frozenset({"td", "th"})+_TABLE_NESTING_TAGS = _TABLE_CELL_TAGS | {"caption"}+_TABLE_SECTION_TAGS = frozenset({"tbody", "tfoot", "thead"})+_TABLE_SECTION_START_TAGS = _TABLE_SECTION_TAGS | {"caption", "col", "colgroup"}+_INDEXED_OPEN_TAGS = _SKIP_RECOVERY_END_TAGS | _SCOPE_BARRIERS+# repeated span cells use half the 16k fetch limit to leave room for text after the table_MAX_SPAN_CHARS = 8_000-# a long rowspan cell is usually page layout, so only its first row keeps the text+# long rowspan cells usually encode layout, so only their first row keeps the text_MAX_REPEATED_CELL_CHARS = 200-# floor per scope candidate once the page-wide total is spent, so an earlier decoy cannot starve a later article+# each scope keeps 256 characters after the page-wide budget is spent, preventing decoy starvation_MIN_SCOPE_SPAN_CHARS = 256_INLINE_EMPHASIS = {"strong": "**", "b": "**", "em": "*", "i": "*"}-# after a word, digits joined by commas / en dashes are citations (claim<sup>1,3–5</sup>); one separator per-# step keeps the match linear. Hyphen / minus stay exponents (10<sup>-3</sup>), and so do thousands (1,000)+# citation lists after words use commas or en dashes; hyphens, minuses, and thousands stay exponents_CITATION_LIST = re.compile(r"\d+(?:\s*[–,]\s*\d+)+")_THOUSANDS = re.compile(r"\d{1,3}(?:,\d{3})+")_PLAIN_SUFFIXES = frozenset(@@ -528,6 +679,8 @@ class _TitleButtonScan:def __init__(self) -> None:self.keep: set[tuple[int, int]] = set() # HTMLParser.getpos() of each kept <button>self._open: list[str] = []+ self._namespaces: list[str] = []+ self._html_integration: list[bool] = []self._closable_open = (0 # open tags with an optional end tag, as _MarkdownRenderer counts them)@@ -540,11 +693,15 @@ class _TitleButtonScan:self._headings: list[list] = []def starttag(self, tag: str, attrs: list[tuple[str, str | None]], pos: tuple[int, int]) -> None:+ attr_dict = dict(attrs)+ self._prepare_foreign_html_start(tag, attr_dict)self._close_implicit(tag)if tag in _VOID_TAGS:return- attr_dict = dict(attrs)+ namespace = self._next_namespace(tag)self._open.append(tag)+ self._namespaces.append(namespace)+ self._html_integration.append(self._is_html_integration_point(tag, namespace, attr_dict))if tag in _IMPLICIT_CLOSERS:self._closable_open += 1index = len(self._open) - 1@@ -577,11 +734,44 @@ class _TitleButtonScan:# a page cut inside a heading (the fetch cap) still keeps its titleself._close_headings(0)+ def _next_namespace(self, tag: str) -> str:+ if not self._namespaces or self._namespaces[-1] == "html":+ return "svg" if tag == "svg" else "math" if tag == "math" else "html"+ if self._html_integration[-1] and not (+ self._namespaces[-1] == "math" and tag in {"mglyph", "malignmark"}+ ):+ return "svg" if tag == "svg" else "math" if tag == "math" else "html"+ return self._namespaces[-1]++ @staticmethod+ def _is_html_integration_point(tag: str, namespace: str, attrs: dict) -> bool:+ if namespace == "svg":+ return tag in _SVG_SCOPE_BARRIERS+ if namespace != "math":+ return False+ if tag in _MATHML_TEXT_INTEGRATION_POINTS:+ return True+ encoding = (attrs.get("encoding") or "").strip().lower()+ return tag == "annotation-xml" and encoding in {"text/html", "application/xhtml+xml"}++ def _prepare_foreign_html_start(self, tag: str, attrs: dict) -> None:+ if not self._open or self._namespaces[-1] == "html":+ return+ if tag not in _FOREIGN_HTML_BREAKOUT_START_TAGS and not (+ tag == "font" and any(name in attrs for name in {"color", "face", "size"})+ ):+ return+ for i in range(len(self._open) - 1, -1, -1):+ if self._namespaces[i] == "html" or self._html_integration[i]:+ self._pop_to(i + 1)+ return+ self._pop_to(0)+def _close_implicit(self, tag: str) -> None:"""The renderer's optional-end-tag recovery (``_MarkdownRenderer._close_implicit``), so both see one tree."""if not self._closable_open:return- barriers = _CLOSE_BARRIERS.get(tag, ())+ barriers = _IMPLICIT_CLOSE_BARRIERS.get(tag, frozenset())while True:close_at = Nonefor i in range(len(self._open) - 1, -1, -1):@@ -607,6 +797,8 @@ class _TitleButtonScan:self._close_headings(i)self._closable_open -= sum(1 for name in self._open[i:] if name in _IMPLICIT_CLOSERS)del self._open[i:]+ del self._namespaces[i:]+ del self._html_integration[i:]def _close_headings(self, i: int) -> None:while self._headings and self._headings[-1][0] >= i:@@ -638,14 +830,20 @@ class _MarkdownRenderer(HTMLParser):page_span_limit: int | None = None,):super().__init__(convert_charrefs = False)- # getpos() of buttons that carry their heading's title, found by _TitleButtonScan+ # parser positions of buttons that carry their heading title, found by _TitleButtonScanself.title_buttons: frozenset[tuple[int, int]] = frozenset()self._title_scan: _TitleButtonScan | None = Noneself._site_links = site_linksself._out: list[str] = []- self._skip_depth: int = 0+ self._skip_tags: list[str] = []+ # tag indices in _skip_tags avoid rescanning the stack for end tags+ self._skip_at: dict[str, list[int]] = {}+ self._skip_ns_at: dict[tuple[str, str], list[int]] = {}+ self._skip_namespaces: list[str] = []+ self._skip_html_at: list[int] = []+ self._skip_html_integration: list[bool] = []+ self._form_pointer: bool = False- # Main-content scoping: emit only while inside a scope tag.self._scope_tags = scope_tagsself._scope_depth: int = 0@@ -655,16 +853,18 @@ class _MarkdownRenderer(HTMLParser):# open non-void tags plus hidden-start indices, so an omitted </p>/</li> cannot leave the renderer stuck hiddenself._open_tags: list[str] = []- # Open tags that can be closed implicitly; zero lets _close_implicit skip the scan.+ # tag indices in _open_tags keep scoped end-tag recovery at constant time+ self._open_at: dict[str, list[int]] = {}+ # zero avoids scanning when no tags can close implicitlyself._closable_open: int = 0self._hidden_marks: list[int] = []- # Open <header> buffers, innermost last. Empty unless strip_header.+ # innermost <header> buffers; empty unless strip_headerself._strip_header = strip_headerself._header_stack: list[_HeaderFrame] = []self.header_decisions: list[bool] = []self._header_decisions = header_decisions- # Furniture chars removed, so a candidate is sized as the page wrote it.+ # furniture chars removed, so a candidate is sized as the page wrote itself._dropped_chars: int = 0self._seg_dropped_start: int = 0self.scope_dropped: list[int] = []@@ -1080,17 +1280,18 @@ class _MarkdownRenderer(HTMLParser):frame = self._header_stack[-1]frame.heading_parts.append(heading_text + "\n\n")frame.heading_chars += len(heading_text)- # Preserved by hand, so tell the gate too or a title-only card reads as body prose.+ # preserve this in the gate so a title-only card is not counted as body proseself._seg_heading_texts.append(heading_text)- # Tag handlers. Structural bookkeeping shared by every start tag (skip/hidden/scope).def _truncate_open_tags(self, index: int) -> None:- """Drop the open-tag stack above *index*, keeping the closable count."""+ """drop open tags above *index* while maintaining the closable count."""for name in self._open_tags[index:]:+ if positions := self._open_at.get(name):+ positions.pop()if name in _IMPLICIT_CLOSERS:self._closable_open -= 1del self._open_tags[index:]- # a <sup> an ancestor closed (<p>x<sup>2</p>) is gone; a kept frame would fill the depth cap+ # discard <sup> frames whose ancestor closed to avoid filling the depth capwhile self._sup_starts and self._sup_starts[-1][0] >= index:self._sup_starts.pop()@@ -1104,7 +1305,7 @@ class _MarkdownRenderer(HTMLParser):for skipped ``<nav>``/``<footer>``, which also close ``<p>``."""if not self._closable_open:return- barriers = _CLOSE_BARRIERS.get(tag, ())+ barriers = _IMPLICIT_CLOSE_BARRIERS.get(tag, frozenset())while True:close_at = Nonefor i in range(len(self._open_tags) - 1, -1, -1):@@ -1193,20 +1394,69 @@ class _MarkdownRenderer(HTMLParser):frame = self._header_stack[-1]chars = len(text.strip())frame.text_chars += chars- # An anchor with no usable href renders as prose, not as a link.+ # anchors without usable hrefs render as proseif not (self._in_link and self._link_href):returnif self._link_seq == frame.outer_link_seq:- # An enclosing anchor closes after the header, too late to credit.+ # enclosing anchors close after the header, too late to creditframe.link_chars += charselse:self._link_header_chars += chars+ @staticmethod+ def _html_start_namespace(tag: str) -> str:+ if tag == "svg":+ return "svg"+ if tag == "math":+ return "math"+ return "html"++ def _skipped_tag_namespace(self, tag: str) -> str:+ if not self._skip_namespaces:+ return self._html_start_namespace(tag)+ parent_namespace = self._skip_namespaces[-1]+ if parent_namespace == "html":+ return self._html_start_namespace(tag)+ if self._skip_html_integration[-1] and not (+ parent_namespace == "math" and tag in {"mglyph", "malignmark"}+ ):+ return self._html_start_namespace(tag)+ return parent_namespace++ @staticmethod+ def _is_html_integration_point(tag: str, namespace: str, attrs: dict) -> bool:+ if namespace == "svg":+ return tag in _SVG_SCOPE_BARRIERS+ if namespace != "math":+ return False+ if tag in _MATHML_TEXT_INTEGRATION_POINTS:+ return True+ encoding = (attrs.get("encoding") or "").strip().lower()+ return tag == "annotation-xml" and encoding in {"text/html", "application/xhtml+xml"}++ def _truncate_skip_tags(self, index: int) -> None:+ for position, name in enumerate(self._skip_tags[index:], start = index):+ self._skip_at[name].pop()+ self._skip_ns_at[(self._skip_namespaces[position], name)].pop()+ while self._skip_html_at and self._skip_html_at[-1] >= index:+ self._skip_html_at.pop()+ del self._skip_tags[index:]+ del self._skip_namespaces[index:]+ del self._skip_html_integration[index:]++ def _clear_skip_tags(self) -> None:+ self._skip_tags.clear()+ self._skip_at.clear()+ self._skip_ns_at.clear()+ self._skip_namespaces.clear()+ self._skip_html_at.clear()+ self._skip_html_integration.clear()+def _enter_tag(self, tag: str, attr_dict: dict) -> bool:- """Track open/hidden/scope state; return True when the tag's content- should be rendered (False = suppressed). Caller runs ``_close_implicit``- first so recovery also fires for skipped tags."""+ """track tag state; run ``_close_implicit`` first so skipped tags trigger recovery."""if tag not in _VOID_TAGS:+ if tag in _INDEXED_OPEN_TAGS:+ self._open_at.setdefault(tag, []).append(len(self._open_tags))self._open_tags.append(tag)if tag in _IMPLICIT_CLOSERS:self._closable_open += 1@@ -1287,6 +1537,84 @@ class _MarkdownRenderer(HTMLParser):self._scope_seg_start = Nonereturn not suppressed+ def _latest_indexed_open_tag(+ self,+ names: frozenset[str],+ after: int = -1,+ ) -> tuple[int, str] | None:+ candidates = (+ (positions[-1], name)+ for name in names+ if (positions := self._open_at.get(name)) and positions[-1] > after+ )+ return max(candidates, default = None)++ def _close_open_target(self, target: int) -> None:+ names = self._open_tags[target:]+ for name in reversed(names):+ self._close_rendered_tag(name)++ def _prepare_heading_start(self, tag: str) -> None:+ if tag not in _HEADING_TAGS or not self._open_tags:+ return+ if self._open_tags[-1] not in _HEADING_TAGS:+ return+ self._close_open_target(len(self._open_tags) - 1)++ def _prepare_sibling_table_start(self) -> bool:+ if not self._in_table:+ return False+ if self._skip_tags and self._skipped_tag_namespace("table") != "html":+ return False+ tables = self._open_at.get("table")+ target = tables[-1] if tables else -1+ if target < 0:+ return True+ if self._latest_indexed_open_tag(_TABLE_NESTING_TAGS, target):+ return False+ if not self._open_target_in_scope("table", target):+ return True+ self._clear_skip_tags()+ self._close_open_target(target)+ return False++ def _prepare_foreign_html_start(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:+ if not self._skip_tags or self._skip_namespaces[-1] == "html":+ return+ if tag not in _FOREIGN_HTML_BREAKOUT_START_TAGS and not (+ tag == "font" and any(name in {"color", "face", "size"} for name, _ in attrs)+ ):+ return+ for i in range(len(self._skip_tags) - 1, -1, -1):+ if self._skip_namespaces[i] == "html" or self._skip_html_integration[i]:+ self._truncate_skip_tags(i + 1)+ return+ self._clear_skip_tags()++ def _prepare_table_start(self, tag: str) -> None:+ if not self._in_table or tag not in _TABLE_ONLY_START_TAGS:+ return+ tables = self._open_at.get("table")+ table = tables[-1] if tables else -1+ if caption := self._latest_indexed_open_tag(frozenset({"caption"}), table):+ self._clear_skip_tags()+ self._close_rendered_tag(caption[1])+ if self._in_cell:+ cell = self._latest_indexed_open_tag(_TABLE_CELL_TAGS, table)+ if cell:+ self._clear_skip_tags()+ self._close_rendered_tag(cell[1])+ if self._in_row and tag not in _TABLE_CELL_TAGS:+ row = self._latest_indexed_open_tag(frozenset({"tr"}), table)+ if row:+ self._clear_skip_tags()+ self._close_rendered_tag(row[1])+ if tag in _TABLE_SECTION_START_TAGS:+ section = self._latest_indexed_open_tag(_TABLE_SECTION_TAGS, table)+ if section:+ self._clear_skip_tags()+ self._close_rendered_tag(section[1])+def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:tag = tag.lower()if self._title_scan is not None:@@ -1294,21 +1622,66 @@ class _MarkdownRenderer(HTMLParser):title_button = (tag == "button" and bool(self.title_buttons) and self.getpos() in self.title_buttons)+ if self._skip_tags and tag == "button" and self._skipped_tag_namespace(tag) == "html":+ button = self._last_skip_position("button", "html")+ if button >= 0 and self._skip_target_in_scope(tag, button):+ self._truncate_skip_tags(button)+ self._prepare_foreign_html_start(tag, attrs)+ if tag in _TABLE_ONLY_START_TAGS and not self._in_table:+ return+ if tag == "table" and self._prepare_sibling_table_start():+ return+ if (+ self._skip_tags+ and tag in _TABLE_ONLY_START_TAGS+ and self._last_skip_position("table", "html") < 0+ ):+ self._prepare_table_start(tag)++ if self._skip_tags:+ if tag not in _VOID_TAGS:+ attr_dict = dict(attrs)+ namespace = self._skipped_tag_namespace(tag)+ template = self._last_skip_position("template", "html")+ if tag == "form" and namespace == "html" and template < 0:+ if self._form_pointer:+ return+ self._form_pointer = True+ position = len(self._skip_tags)+ self._skip_at.setdefault(tag, []).append(position)+ self._skip_ns_at.setdefault((namespace, tag), []).append(position)+ self._skip_tags.append(tag)+ self._skip_namespaces.append(namespace)+ if namespace == "html":+ self._skip_html_at.append(position)+ self._skip_html_integration.append(+ self._is_html_integration_point(tag, namespace, attr_dict)+ )+ return- if self._skip_depth:- if tag in _SKIP_TAGS:- self._skip_depth += 1+ if tag == "form" and self._form_pointer:return- # Recover optional end tags before the skip decision: a skipped <nav>/<footer> still implicitly closes an open- # <p>, releasing its hidden mark so following siblings render.+ # close optional tags before skipping so skipped <nav>/<footer> releases an open <p> markerself._close_implicit(tag)+ self._prepare_heading_start(tag)+ self._prepare_table_start(tag)if tag in _SKIP_TAGS and not (title_button and self._heading_marks):- self._skip_depth += 1+ self._skip_tags.append(tag)+ self._skip_at = {tag: [0]}+ namespace = self._html_start_namespace(tag)+ self._skip_ns_at = {(namespace, tag): [0]}+ self._skip_namespaces = [namespace]+ self._skip_html_at = [0] if namespace == "html" else []+ self._skip_html_integration = [+ self._is_html_integration_point(tag, namespace, dict(attrs))+ ]returnattr_dict = dict(attrs)+ if tag == "form":+ self._form_pointer = Trueif not self._enter_tag(tag, attr_dict):return@@ -1425,7 +1798,7 @@ class _MarkdownRenderer(HTMLParser):self._next_cell_seq += 1self._cell_seq = self._next_cell_seqself._cell_colspan = min(max(1, _span_attr(attr_dict, "colspan")), 1000)- # rowspan="0" runs to the end of the row group+ # rowspan="0" spans the remaining row groupself._cell_rowspan = _span_attr(attr_dict, "rowspan") or 65534if tag == "th":self._row_has_th = True@@ -1438,15 +1811,64 @@ class _MarkdownRenderer(HTMLParser):if self._title_scan is not None:self._title_scan.endtag(tag)- # a kept title button closes through _exit_tag; skipped ones always raised _skip_depth- if tag in _SKIP_TAGS and (self._skip_depth or tag != "button"):- self._skip_depth = max(0, self._skip_depth - 1)+ recovered_target = -1+ if self._skip_tags:+ at = self._skip_at.get(tag)+ template = self._last_skip_position("template", "html")+ if tag == "form" and template < 0:+ if at and self._skip_namespaces[at[-1]] == "html":+ self._form_pointer = False+ elif not (+ at+ and self._skip_namespaces[at[-1]] != "html"+ and (not self._skip_html_at or self._skip_html_at[-1] <= at[-1])+ ):+ self._form_pointer = False+ return+ # template is a scope boundary, so end tags outside it are ignored+ if at and (template < 0 or at[-1] >= template):+ i = at[-1]+ if not self._skip_target_in_scope(tag, i):+ return+ if tag in _GENERIC_END_SKIP_TAGS and self._skip_barrier_after(+ _SPECIAL_HTML_TAGS, "html", i+ ):+ return+ self._truncate_skip_tags(i)+ return+ # only scoped structural end tags pop skipped elements; form and inline end tags do not+ if tag not in _SKIP_RECOVERY_END_TAGS:+ return+ if tag in _HEADING_TAGS:+ heading = self._latest_indexed_open_tag(_HEADING_TAGS)+ target = heading[0] if heading else -1+ else:+ positions = self._open_at.get(tag)+ target = positions[-1] if positions else -1+ if target < 0 or not self._open_target_in_scope(tag, target):+ return+ self._clear_skip_tags()+ recovered_target = target+ # kept title buttons close through _exit_tag+ elif tag in _SKIP_TAGS and tag != "button":+ return++ if tag == "form":+ self._form_pointer = False++ if recovered_target >= 0:+ self._close_open_target(recovered_target)return- if self._skip_depth:+ if tag in _HEADING_TAGS:+ heading = self._latest_indexed_open_tag(_HEADING_TAGS)+ if heading and self._open_target_in_scope(tag, heading[0]):+ self._close_open_target(heading[0])return+ self._close_rendered_tag(tag)+ def _close_rendered_tag(self, tag: str) -> None:closing_sup = None- # O(1): only a <sup> that is still the innermost open tag converts; malformed nesting drops on unwind+ # only the innermost open <sup> converts in O(1); malformed nesting drops on unwindif (tag == "sup"and self._sup_starts@@ -1518,8 +1940,59 @@ class _MarkdownRenderer(HTMLParser):elif tag == "table":self._finish_table()+ @staticmethod+ def _scope_barriers(tag: str) -> frozenset[str]:+ if tag == "li":+ return _LIST_ITEM_SCOPE_BARRIERS+ if tag == "p":+ return _BUTTON_SCOPE_BARRIERS+ if tag in _TABLE_END_TAGS:+ return _TABLE_SCOPE_BARRIERS+ return _SCOPE_BARRIERS++ def _last_skip_position(self, tag: str, namespace: str) -> int:+ positions = self._skip_ns_at.get((namespace, tag))+ return positions[-1] if positions else -1++ def _skip_barrier_after(self, names: frozenset[str], namespace: str, target: int) -> bool:+ return any(self._last_skip_position(name, namespace) > target for name in names)++ def _foreign_skip_barrier_after(self, target: int) -> bool:+ return self._skip_barrier_after(+ _SVG_SCOPE_BARRIERS, "svg", target+ ) or self._skip_barrier_after(_MATHML_SCOPE_BARRIERS, "math", target)++ def _skip_target_in_scope(self, tag: str, target: int) -> bool:+ # nothing above the innermost element can be a barrier+ if target == len(self._skip_tags) - 1:+ return True+ barriers = self._scope_barriers(tag)+ if self._skip_barrier_after(barriers, "html", target):+ return False+ target_namespace = self._skip_namespaces[target]+ if target_namespace != "html" and (+ not self._skip_html_at or self._skip_html_at[-1] <= target+ ):+ return True+ return not self._foreign_skip_barrier_after(target)++ def _open_skip_barrier(self, barriers: frozenset[str]) -> bool:+ return self._skip_barrier_after(barriers, "html", -1) or self._foreign_skip_barrier_after(+ -1+ )++ def _open_target_in_scope(self, tag: str, target: int) -> bool:+ barriers = self._scope_barriers(tag)+ if self._open_skip_barrier(barriers):+ return False+ return not any(+ positions and positions[-1] > target+ for name in barriers+ if (positions := self._open_at.get(name))+ )+def _text_suppressed(self) -> bool:- if self._skip_depth or self._hidden_marks:+ if self._skip_tags or self._hidden_marks:return Truereturn self._scope_tags is not None and self._scope_depth == 0diff --git a/studio/backend/tests/test_web_fetch_extraction.py b/studio/backend/tests/test_web_fetch_extraction.pyindex dfc0da83bf6..7e6bb8cffd1 100644--- a/studio/backend/tests/test_web_fetch_extraction.py+++ b/studio/backend/tests/test_web_fetch_extraction.py@@ -327,9 +327,7 @@ def test_hidden_regions_with_inline_children_end_at_the_implied_close(def test_skipped_tag_implicitly_closes_hidden_paragraph():- # A skipped block (<nav>/<footer>) also closes an open <p>. The optional-close- # bookkeeping must run before the skip, or the never-closed <p hidden> keeps its- # hidden mark and swallows every following sibling.+ # optional-close bookkeeping must run before skipped blocks or an unclosed hidden paragraph hides later siblingsfor skipped in ("nav", "footer"):html = f"<body><p hidden>secret<{skipped}>chrome</{skipped}>VISIBLE</body>"out = html_to_markdown(html)@@ -338,6 +336,396 @@ def test_skipped_tag_implicitly_closes_hidden_paragraph():assert "VISIBLE" in out[email protected]("skipped", ["nav", "footer", "button"])[email protected]("main_content", [False, True])+def test_skipped_tag_closed_by_its_parent_keeps_the_rest_of_the_page(skipped, main_content):+ html = (+ f"<body><div><{skipped}><div><a href=/x>Menu</a></div></div>"+ "<main><h1>Title</h1><p>Real text of the page that must reach the model.</p></main></body>"+ )+ out = html_to_markdown(html, main_content = main_content)+ assert "Menu" not in out+ assert "Real text of the page" in out++[email protected]("main_content", [False, True])+def test_html_block_start_breaks_out_of_svg(main_content):+ html = (+ "<body><div><svg><div><a href=/x>Menu</a></div></div>"+ "<main><h1>Title</h1><p>Real text of the page.</p></main></body>"+ )+ out = html_to_markdown(html, main_content = main_content)+ assert "Menu" in out+ assert "Real text of the page" in out++[email protected]("main_content", [False, True])+def test_heading_button_after_foreign_breakout_is_kept(main_content):+ html = "<svg><h1><button>Title</button></h1><p>Body text</p>"+ out = html_to_markdown(html, main_content = main_content)+ assert "Title" in out and "Body text" in out+++ "outside",+ [+ "<div><template><p>Hidden</div><p>Template text</p></template></div>",+ "<nav><template><p>Hidden</nav><p>Template text</p></template></nav>",+ ],+)+def test_end_tag_outside_a_template_keeps_it_skipped(outside):+ out = html_to_markdown(outside + "<p>After</p>")+ assert "Hidden" not in out and "Template text" not in out+ assert "After" in out+++ "html",+ [+ "<form><nav>Hidden</form>Menu text</nav><p>After</p>",+ "<span><nav>Hidden</span>Menu text</nav><p>After</p>",+ "<a><nav>Hidden</a>Menu text</nav><p>After</p>",+ "<b><nav>Hidden</b>Menu text</nav><p>After</p>",+ "<div><select><option>Hidden</div>Menu text</select></div><p>After</p>",+ (+ "<div><table><tr><td><nav>Hidden</div>Menu text</nav></td></tr></table>"+ "</div><p>After</p>"+ ),+ "<nav><table><tr><td>Hidden</nav>Menu text</td></tr></table></nav><p>After</p>",+ "<nav><select><option>Hidden</nav>Menu text</select></nav><p>After</p>",+ "<body><nav>Hidden</body>Menu text</nav><p>After</p>",+ ],+)[email protected]("main_content", [False, True])+def test_ancestor_end_tag_that_does_not_pop_a_skipped_element_keeps_it_skipped(html, main_content):+ out = html_to_markdown(html, main_content = main_content)+ assert "Hidden" not in out and "Menu text" not in out+ assert "After" in out++[email protected]("main_content", [False, True])+def test_matching_skipped_root_cannot_close_across_select_scope(main_content):+ html = "<datalist><select><option>Hidden</datalist>Menu text</select></datalist><p>After</p>"+ out = html_to_markdown(html, main_content = main_content)+ assert "Hidden" not in out and "Menu text" not in out+ assert "After" in out++[email protected]("main_content", [False, True])+def test_dialog_skip_does_not_recover_through_implicitly_closed_paragraph(main_content):+ html = "<p>intro<dialog>Hidden</p>Menu text</dialog><p>After</p>"+ out = html_to_markdown(html, main_content = main_content)+ assert "Hidden" not in out and "Menu text" not in out+ assert "intro" in out and "After" in out++[email protected]("block", ["center", "dir", "listing", "search", "summary"])[email protected]("main_content", [False, True])+def test_block_start_closes_paragraph_before_skipped_form_chrome(block, main_content):+ html = f"<p>intro<{block}><datalist>Hidden</p>Menu text</datalist></{block}><p>After</p>"+ out = html_to_markdown(html, main_content = main_content)+ assert "Hidden" not in out and "Menu text" not in out+ assert "intro" in out and "After" in out++[email protected]("main_content", [False, True])+def test_paragraph_start_recovery_stops_at_button_scope_barrier(main_content):+ html = "<p hidden><object><center>SECRET</center></object><p>AFTER</p>"+ out = html_to_markdown(html, main_content = main_content)+ assert "SECRET" not in out+ assert "AFTER" in out++[email protected]("table_tag", ["caption", "tbody", "td", "tfoot", "th", "thead", "tr"])[email protected]("main_content", [False, True])+def test_table_only_tag_outside_table_cannot_recover_skipped_content(table_tag, main_content):+ html = f"<{table_tag}><nav>Hidden</{table_tag}>Menu text</nav><p>After</p>"+ out = html_to_markdown(html, main_content = main_content)+ assert "Hidden" not in out and "Menu text" not in out+ assert "After" in out++[email protected]("main_content", [False, True])+def test_caption_start_closes_the_active_cell_before_skip_recovery(main_content):+ html = "<table><tr><td><caption><nav>Hidden</td>Menu text</nav></caption></table><p>After</p>"+ out = html_to_markdown(html, main_content = main_content)+ assert "Hidden" not in out and "Menu text" not in out+ assert "After" in out++[email protected]("main_content", [False, True])+def test_table_cell_start_reconciles_while_content_is_skipped(main_content):+ html = "<table><tr><td><nav>Hidden<td></nav>Visible</td></tr></table>"+ out = html_to_markdown(html, main_content = main_content)+ assert "Hidden" not in out+ assert "Visible" in out++[email protected]("main_content", [False, True])+def test_nested_button_start_replaces_outer_skipped_button(main_content):+ html = "<button>Title<button>Inner</button><nav>Hidden</button>Menu text</nav><p>After</p>"+ out = html_to_markdown(html, main_content = main_content)+ assert "Title" not in out and "Inner" not in out+ assert "Hidden" not in out and "Menu text" not in out+ assert "After" in out++[email protected]("foreign", ["<svg><g>", "<math><mrow>"])[email protected]("main_content", [False, True])+def test_foreign_button_start_does_not_close_html_button(foreign, main_content):+ closing = "</g></svg>" if foreign.startswith("<svg") else "</mrow></math>"+ html = (+ f"<button>Title{foreign}<button>Inner</button>{closing}"+ "<nav>Hidden</button>Menu text</nav><p>After</p>"+ )+ out = html_to_markdown(html, main_content = main_content)+ assert "Title" not in out and "Inner" not in out and "Hidden" not in out+ assert "Menu text" in out and "After" in out++[email protected]("root, descendant", [("svg", "foreignObject"), ("math", "mi")])[email protected]("main_content", [False, True])+def test_foreign_root_end_closes_through_foreign_descendant(root, descendant, main_content):+ html = f"<{root}><{descendant}>Hidden</{root}><p>Real text</p>"+ out = html_to_markdown(html, main_content = main_content)+ assert "Hidden" not in out+ assert "Real text" in out++[email protected]("main_content", [False, True])+def test_foreign_end_tag_closes_through_integration_point(main_content):+ html = "<svg><g><foreignObject></g><p>Visible</p></svg><p>After</p>"+ out = html_to_markdown(html, main_content = main_content)+ assert "Visible" in out and "After" in out++[email protected]("main_content", [False, True])+def test_foreign_breakout_keeps_html_skipped_ancestor(main_content):+ html = "<nav><svg><g><foreignObject></g><p>Hidden</p></nav><p>After</p>"+ out = html_to_markdown(html, main_content = main_content)+ assert "Hidden" not in out+ assert "After" in out+++ "html",+ [+ "<svg><foreignObject><div>Hidden</svg>Menu text</div></foreignObject></svg>",+ "<math><mtext><div>Hidden</math>Menu text</div></mtext></math>",+ ],+)[email protected]("main_content", [False, True])+def test_foreign_root_end_stops_at_html_integration_descendant(html, main_content):+ out = html_to_markdown(html + "<p>After</p>", main_content = main_content)+ assert "Hidden" not in out and "Menu text" not in out+ assert "After" in out++[email protected]("main_content", [False, True])+def test_generic_datalist_end_stops_at_special_descendant(main_content):+ html = "<datalist><nav>Hidden</datalist>Menu text</nav></datalist><p>After</p>"+ out = html_to_markdown(html, main_content = main_content)+ assert "Hidden" not in out and "Menu text" not in out+ assert "After" in out++[email protected]("skipped", ["dialog", "footer", "nav"])[email protected]("main_content", [False, True])+def test_scoped_block_skip_end_pops_special_descendant(skipped, main_content):+ html = f"<{skipped}><div>Hidden</{skipped}><main>Visible article</main>"+ out = html_to_markdown(html, main_content = main_content)+ assert "Hidden" not in out+ assert "Visible article" in out++[email protected]("main_content", [False, True])+def test_nested_form_start_is_ignored_before_datalist_end(main_content):+ html = "<form><datalist>Hidden<form>ignored</datalist><p>Visible article</p></form>"+ out = html_to_markdown(html, main_content = main_content)+ assert "Hidden" not in out and "ignored" not in out+ assert "Visible article" in out++[email protected]("main_content", [False, True])+def test_foreign_form_end_clears_html_form_pointer(main_content):+ html = "<form><svg><g>Hidden</form></g></svg><form hidden><p>SECRET</p></form><p>After</p>"+ out = html_to_markdown(html, main_content = main_content)+ assert "Hidden" not in out and "SECRET" not in out+ assert "After" in out++[email protected]("main_content", [False, True])+def test_matching_foreign_form_end_keeps_html_form_pointer(main_content):+ html = "<form><svg><form>Hidden</form></svg><form hidden><p>SECRET</p></form><p>After</p>"+ out = html_to_markdown(html, main_content = main_content)+ assert "Hidden" not in out+ assert "SECRET" in out and "After" in out++[email protected]("item", ["dd", "dt", "li"])[email protected]("main_content", [False, True])+def test_list_item_start_closes_paragraph_before_skip_recovery(item, main_content):+ html = f"<p>intro<{item}><datalist>Hidden</p>Menu text</datalist><p>After</p>"+ out = html_to_markdown(html, main_content = main_content)+ assert "Hidden" not in out and "Menu text" not in out+ assert "intro" in out and "After" in out++[email protected]("heading", ["h1", "h2", "h3", "h4", "h5", "h6"])[email protected]("main_content", [False, True])+def test_heading_start_closes_open_heading_before_skip_recovery(heading, main_content):+ html = f"<{heading}>Title<h2>Sub</h2><nav>Hidden</{heading}>Menu text</nav><p>After</p>"+ out = html_to_markdown(html, main_content = main_content)+ assert "Title" in out and "Sub" in out and "After" in out+ assert "Hidden" not in out and "Menu text" not in out++[email protected]("main_content", [False, True])+def test_heading_start_only_pops_a_current_heading(main_content):+ html = "<h1><span>Title<h2>Sub</h2><nav>Hidden</h1>Menu text</nav><p>After</p>"+ out = html_to_markdown(html, main_content = main_content)+ assert "Title" in out and "Sub" in out and "Menu text" in out and "After" in out+ assert "Hidden" not in out++[email protected]("main_content", [False, True])+def test_mismatched_heading_end_reconciles_before_skip_recovery(main_content):+ html = "<h1>Title</h2><nav>Hidden</h1>Menu text</nav><p>After</p>"+ out = html_to_markdown(html, main_content = main_content)+ assert "Title" in out and "After" in out+ assert "Hidden" not in out and "Menu text" not in out++[email protected]("main_content", [False, True])+def test_table_start_closes_active_table_outside_cell(main_content):+ html = "<table><table><tr><td>X</td></tr></table><nav>Hidden</table>Menu text</nav><p>After</p>"+ out = html_to_markdown(html, main_content = main_content)+ assert "X" in out and "After" in out+ assert "Hidden" not in out and "Menu text" not in out++[email protected]("main_content", [False, True])+def test_table_start_pops_skipped_descendant_of_active_table(main_content):+ html = "<table><nav>Hidden<table><tr><td>X</td></tr></table><p>After</p>"+ out = html_to_markdown(html, main_content = main_content)+ assert "Hidden" not in out+ assert "X" in out and "After" in out++[email protected]("main_content", [False, True])+def test_table_start_inside_caption_remains_nested(main_content):+ html = (+ "<table><caption><nav>Hidden<table><tr><td>X</td></tr></table>"+ "Menu text</nav></caption></table><p>After</p>"+ )+ out = html_to_markdown(html, main_content = main_content)+ assert "Hidden" not in out and "X" not in out and "Menu text" not in out+ assert "After" in out++[email protected]("main_content", [False, True])+def test_custom_select_keeps_table_and_following_paragraph_suppressed(main_content):+ html = "<select><table>Hidden</select><p>Real text</p>"+ assert html_to_markdown(html, main_content = main_content) == ""+++ "html",+ [+ "<section><nav>Hidden</section><p>Visible text</p>",+ "<ul><li><nav>Hidden</li><li>Visible text</li></ul>",+ "<table><tr><td><nav>Hidden</td><td>Visible text</td></tr></table>",+ "<h1><nav>Hidden</h2><p>Visible text</p>",+ ],+)[email protected]("main_content", [False, True])+def test_ancestor_end_tag_that_pops_a_skipped_element_ends_suppression(html, main_content):+ out = html_to_markdown(html, main_content = main_content)+ assert "Hidden" not in out+ assert "Visible text" in out+++ "opening",+ ["<blockquote>", "<pre>", "<a href='/real'>", "<ol><li>"],+)+def test_recovered_ancestor_flushes_open_content_buffers_before_scoring(opening):+ real = "real article prose " * 20+ decoy = "unrelated decoy prose " * 20+ html = f"<article>{opening}{real}<nav>Hidden</article><main><p>{decoy}</p></main>"+ out = html_to_markdown(html, main_content = True)+ assert "real article prose" in out+ assert "unrelated decoy prose" not in out+++def test_mismatched_heading_recovery_closes_the_open_heading_before_scoring():+ real = "real article prose " * 20+ decoy = "unrelated decoy prose " * 20+ html = (+ f"<article><h1>Real title<nav>Hidden</h2><p>{real}</p></article>"+ f"<main><p>{decoy}</p></main>"+ )+ out = html_to_markdown(html, main_content = True)+ assert "real article prose" in out+ assert "unrelated decoy prose" not in out+++ "foreign",+ [+ "<svg><foreignObject><p>Hidden</div>Menu text</p></foreignObject></svg>",+ "<svg><desc><p>Hidden</div>Menu text</p></desc></svg>",+ "<svg><title>Hidden</div>Menu text</title></svg>",+ "<math><mi><p>Hidden</div>Menu text</p></mi></math>",+ "<math><mo><p>Hidden</div>Menu text</p></mo></math>",+ "<math><mn><p>Hidden</div>Menu text</p></mn></math>",+ "<math><ms><p>Hidden</div>Menu text</p></ms></math>",+ "<math><mtext><p>Hidden</div>Menu text</p></mtext></math>",+ '<math><annotation-xml encoding="text/html"><p>Hidden</div>Menu text</p>'+ "</annotation-xml></math>",+ '<math><annotation-xml encoding="application/xhtml+xml"><p>Hidden</div>Menu text</p>'+ "</annotation-xml></math>",+ ],+)[email protected]("main_content", [False, True])+def test_foreign_content_scope_barriers_keep_skipped_text_hidden(foreign, main_content):+ html = f"<div>{foreign}</div><p>After</p>"+ out = html_to_markdown(html, main_content = main_content)+ assert "Hidden" not in out and "Menu text" not in out+ assert "After" in out+++def test_html_element_named_like_foreign_barrier_does_not_block_recovery():+ html = "<div><nav><foreignobject>Hidden</div>Visible</foreignobject></nav><p>After</p>"+ out = html_to_markdown(html)+ assert "Hidden" not in out+ assert "Visible" in out and "After" in out+++ "build",+ [+ lambda n: "<body><nav><ul>" + "<li>x" * n + "</a>" * n + "</ul></nav>",+ lambda n: "<body>"+ + "<div>" * n+ + "<nav><template>x"+ + "</div>" * n+ + "</template>"+ + "</span>" * n,+ ],+)+def test_stray_end_tags_in_a_skipped_menu_stay_linear(build):+ import time++ timings = []+ for count in (1000, 8000):+ start = time.perf_counter()+ html_to_markdown(build(count), main_content = True)+ timings.append(time.perf_counter() - start)+ # eight times the input should remain well below quadratic growth+ assert timings[1] < timings[0] * 24, timings++@pytest.mark.parametrize("html, heading",[