Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: keep list numbers in Word and HTML knowledge base files (#13755)
Nilay1a76e8885314
diff --git a/studio/backend/core/rag/parsers.py b/studio/backend/core/rag/parsers.pyindex 830f544c024..d28003ad202 100644--- a/studio/backend/core/rag/parsers.py+++ b/studio/backend/core/rag/parsers.py@@ -61,6 +61,14 @@ _HTML_PRE_TAGS = frozenset(("listing", "plaintext", "pre", "textarea", "xmp"))# atomic inline boxes separate neighbouring text without breaking the line_HTML_BOX_TAGS = frozenset(("button", "img", "input", "select"))_HTML_ROW_GROUPS = frozenset(("thead", "tbody", "tfoot"))+_HTML_LIST_TAGS = frozenset(("dir", "menu", "ol", "ul"))+_HTML_LIST_FORMATS = {+ "1": "decimal",+ "a": "lowerAlpha",+ "A": "upperAlpha",+ "i": "lowerRoman",+ "I": "upperRoman",+}_HTML_TABLE_DEPTH = 32@@ -80,6 +88,11 @@ class _HtmlTable:self.spans: list[int] = []+def _html_int(value) -> int | None:+ match = re.match(r"\s*([+-]?\d{1,18})(?!\d)", value or "")+ return int(match.group(1)) if match else None++def _html_span(attrs, name: str, limit: int) -> int:try:value = int(dict(attrs).get(name) or 1)@@ -102,11 +115,18 @@ class _Stripper(HTMLParser):self._tables: list[_HtmlTable] = []self._span_budget = span_budgetself._deep = 0+ self._lists: list[tuple[str, dict | None, list]] = []+ self._open_lists: dict[str, int] = {}+ self.labels: list[str] = []+ self.nonce = secrets.token_hex(4)+ self._label: str | None = Nonedef _in_table(self) -> bool:return bool(self._tables) and not self._skip and not self._deepdef _end_cell(self) -> None:+ if self.out is not self._tables[-1].sink:+ self._emit_label()self._flush()self.out = self._tables[-1].sink@@ -182,6 +202,29 @@ class _Stripper(HTMLParser):row.append(None if i else cell)self.out = cell+ def _end_list(self) -> str:+ tag, attrs, items = self._lists.pop()+ self._open_lists[tag] -= 1+ if attrs is not None:+ backwards = "reversed" in attrs+ number = _html_int(attrs.get("start"))+ if number is None:+ number = len(items) if backwards else 1+ kind = _HTML_LIST_FORMATS.get(attrs.get("type") or "")+ for index, value, item_kind in items:+ number = number if value is None else value+ item_format = _HTML_LIST_FORMATS.get(item_kind or "", kind)+ self.labels[index] = _list_number(number, item_format) + "."+ number += -1 if backwards else 1+ return tag++ def _emit_label(self) -> None:+ if self._label:+ self._flush()+ self._line.append(self._label)+ self._label = None+ self._flush()+def _flush(self) -> None:text = "".join(self._line)self._line = []@@ -219,6 +262,17 @@ class _Stripper(HTMLParser):self._tables.append(_HtmlTable(self.out, nested))if tag in _HTML_PRE_TAGS:self._pre += 1+ if tag in _HTML_LIST_TAGS or tag == "li":+ self._emit_label()+ if tag in _HTML_LIST_TAGS:+ self._lists.append((tag, dict(attrs) if tag == "ol" else None, []))+ self._open_lists[tag] = self._open_lists.get(tag, 0) + 1+ elif tag == "li" and self._lists and self._lists[-1][1] is not None:+ attrs = dict(attrs)+ item = (len(self.labels), _html_int(attrs.get("value")), attrs.get("type"))+ self._lists[-1][2].append(item)+ self._label = f"\ue000{self.nonce}.{len(self.labels)}\ue001 "+ self.labels.append("")elif tag in _HTML_BOX_TAGS and not self._skip and not self._pre:self._line.append(" ")elif tag == "tspan" and not self._skip and any(k in ("x", "y") for k, _ in attrs):@@ -250,11 +304,18 @@ class _Stripper(HTMLParser):self._deep -= 1if tag in _HTML_PRE_TAGS and self._pre:self._pre -= 1+ if self._open_lists.get(tag):+ self._emit_label()+ while self._end_list() != tag:+ passelif tag in _HTML_BOX_TAGS and not self._skip and not self._pre:self._line.append(" ")def handle_data(self, data):if not self._skip:+ if self._label and data.strip():+ self._line.append(self._label)+ self._label = Noneself._line.append(data)def close(self):@@ -264,14 +325,19 @@ class _Stripper(HTMLParser):table = self._tables.pop()if table.nested:self.out.append(None)+ self._emit_label()self._flush()+ while self._lists:+ self._end_list()def _html(raw: str) -> list[Page]:parser = _Stripper(len(raw))parser.feed(raw)parser.close()- return [_page("\n".join(parser.out), 1)]+ label = re.compile(f"\ue000{parser.nonce}\\.(\\d+)\ue001")+ text = label.sub(lambda match: parser.labels[int(match.group(1))], "\n".join(parser.out))+ return [_page(text, 1)]# pymupdf4llm can corrupt positioned RTL and Indic glyphs; use logical-order@@ -828,6 +894,214 @@ def _docx_paragraph_text(paragraph) -> str:)+def _docx_int(value) -> int:+ try:+ return max(-(10**18), min(int(value or 0), 10**18))+ except ValueError:+ return 0+++def _docx_number_lists(document) -> None:+ from docx.opc.constants import RELATIONSHIP_TYPE as RT+ from docx.oxml import OxmlElement, parse_xml++ def related(reltype):+ part = next(+ (+ r.target_part+ for r in document.part.rels.values()+ if r.reltype == reltype and not r.is_external+ ),+ None,+ )+ if part is None:+ return None+ return part.element if hasattr(part, "element") else parse_xml(part.blob)++ def val(node, name):+ child = None if node is None else node.find(_W + name)+ return None if child is None else child.get(_W + "val") or None++ def first_by_level(nodes):+ by_level = {}+ for node in nodes:+ by_level.setdefault(node.get(_W + "ilvl"), node)+ return by_level++ numbering = related(RT.NUMBERING)+ if numbering is None:+ return+ styles = related(RT.STYLES)+ style_by_id = {+ style.get(_W + "styleId"): style+ for style in (() if styles is None else styles.iterchildren(_W + "style"))+ }+ default_style = next(+ (+ style_id+ for style_id, style in style_by_id.items()+ if style.get(_W + "type") == "paragraph"+ and style.get(_W + "default") in ("1", "true", "on")+ ),+ None,+ )+ abstracts = {a.get(_W + "abstractNumId"): a for a in numbering.iterchildren(_W + "abstractNum")}+ nums = {n.get(_W + "numId"): n for n in numbering.iterchildren(_W + "num")}++ # numId and ilvl inherit through basedOn independently, like any other paragraph property.+ def style_num(+ style_id,+ name,+ depth = 0,+ ):+ style = style_by_id.get(style_id)+ if style is None or depth > 20:+ return None+ value = val(style.find(f"{_W}pPr/{_W}numPr"), name)+ return style_num(val(style, "basedOn"), name, depth + 1) if value is None else value++ def linked(abstract_id, depth = 0):+ num_id = style_num(val(abstracts.get(abstract_id), "numStyleLink"), "numId")+ target = val(nums.get(num_id), "abstractNumId")+ if target in (None, abstract_id) or depth > 5:+ return abstract_id+ return linked(target, depth + 1)++ instances = {}++ def instance(num_id):+ if num_id in instances:+ return instances[num_id]+ num = nums.get(num_id)+ abstract_id = linked(val(num, "abstractNumId"))+ abstract = abstracts.get(abstract_id)+ instances[num_id] = None+ if num is None or abstract is None:+ return None+ overrides = first_by_level(num.iterchildren(_W + "lvlOverride"))+ defined = first_by_level(abstract.iterchildren(_W + "lvl"))+ levels = []+ for index in range(9):+ override = overrides.get(str(index))+ lvl = None if override is None else override.find(_W + "lvl")+ lvl = defined.get(str(index)) if lvl is None else lvl+ legal = lvl is not None and any(+ node.get(_W + "val", "true") not in ("0", "false", "off")+ for node in lvl.iterchildren(_W + "isLgl")+ )+ start = _docx_int(val(override, "startOverride") or val(lvl, "start"))+ fmt, restart, text = (val(lvl, key) for key in ("numFmt", "lvlRestart", "lvlText"))+ levels.append((lvl, start, fmt, restart, legal, text or ""))+ restarts = [+ int(at)+ for at, node in overrides.items()+ if at in tuple("012345678") and node.find(_W + "startOverride") is not None+ ]+ by_style = {}+ for index, (lvl, *_) in enumerate(levels):+ by_style.setdefault(val(lvl, "pStyle"), index)+ instances[num_id] = (abstract_id, levels, restarts, by_style)+ return instances[num_id]++ w15 = "{http://schemas.microsoft.com/office/word/2012/wordml}"+ restart_after_break = {+ linked(abstract_id)+ for abstract_id, abstract in abstracts.items()+ if abstract.get(w15 + "restartNumberingAfterBreak") in ("1", "true", "on")+ }+ counters: dict[str, list] = {}+ started: set[str] = set()+ restartable: set[str] = set()++ def label(p_pr):+ mark = None if p_pr is None else p_pr.find(_W + "rPr")+ if mark is not None and (+ mark.find(_W + "del") is not None or mark.find(_W + "moveFrom") is not None+ ):+ return None+ direct = None if p_pr is None else p_pr.find(_W + "numPr")+ style = style_id = val(p_pr, "pStyle") or default_style+ num_id = val(direct, "numId") or style_num(style, "numId")+ found = None if num_id is None else instance(num_id)+ if found is None:+ return None+ abstract_id, levels, restarts, by_style = found+ # A heading style's numPr often names only the list, not the level.+ linked_level = None+ for _ in range(21):+ if style is None or linked_level is not None:+ break+ linked_level = by_style.get(style)+ style = val(style_by_id.get(style), "basedOn")+ ilvl = val(direct, "ilvl") or style_num(style_id, "ilvl") or linked_level+ ilvl = min(8, max(0, _docx_int(ilvl)))+ lvl, _, fmt, _, legal, text = levels[ilvl]+ if lvl is None:+ return None+ # Word shares counters across instances of one abstract; a startOverride restarts them once.+ counts = counters.setdefault(abstract_id, [None] * 9)+ if abstract_id in restart_after_break:+ restartable.add(abstract_id)+ if num_id not in started:+ started.add(num_id)+ for at in restarts:+ counts[at:] = [None] * (9 - at)+ for i in range(ilvl):+ if counts[i] is None:+ counts[i] = levels[i][1]+ counts[ilvl] = levels[ilvl][1] if counts[ilvl] is None else counts[ilvl] + 1+ for i in range(ilvl + 1, 9):+ restart = levels[i][3]+ if restart is None or ilvl < _docx_int(restart):+ counts[i] = None+ if fmt == "bullet" or len(text) > 256:+ return None+ value = ""+ for index, piece in enumerate(re.split("%([1-9])", text)):+ if index % 2 == 0:+ value += piece+ else:+ _, start, piece_fmt, *_ = levels[int(piece) - 1]+ if legal and piece_fmt != "none" and not (piece_fmt or "").startswith("decimal"):+ piece_fmt = "decimal"+ count = counts[int(piece) - 1]+ value += _list_number(start if count is None else count, piece_fmt)+ if len(value) > 256:+ return None+ return value if value.strip() else None++ body = document.element.body+ hidden = _DOCX_SKIP_RUNS_UNDER - {_W + "txbxContent"}+ labels = []+ budget = 1 << 20+ for p in body.iter(_W + "p"):+ if _docx_inside(p, body, hidden):+ # Word still counts a numbered paragraph that only holds placeholder text.+ if not any(node.tag in hidden for node in p.iterancestors()):+ label(p.find(_W + "pPr"))+ continue+ p_pr = p.find(_W + "pPr")+ value = label(p_pr)+ if value is not None:+ labels.append((p, p_pr, value))+ budget -= len(value)+ if budget < 0:+ return+ if p_pr is not None and restartable and p_pr.find(_W + "sectPr") is not None:+ for abstract_id in restartable:+ counters.pop(abstract_id, None)+ restartable.clear()+ for p, p_pr, value in labels:+ text = OxmlElement("w:t")+ text.text = f"{value} "+ run = OxmlElement("w:r")+ run.append(text)+ if p_pr is None:+ p.insert(0, run)+ else:+ p_pr.addnext(run)++def _docx_table_rows(table) -> list[str]:"""Each row as pipe-joined cell text (the locator splits anchors on pipes).Columns stay aligned to the layout grid (merged cells fill their spanned slots,@@ -901,6 +1175,10 @@ def _docx(path: str) -> list[Page]:document = _open_word(path)lines: list[str] = []_docx_unwrap_table_controls(document.element.body)+ try:+ _docx_number_lists(document)+ except Exception as exc:+ logger.warning("Could not number lists in %s: %s", os.path.basename(path), exc)label_notes = _docx_mark_notes(document)# Walk body content in document order: paragraphs alone drop tables entirely.for block in _docx_blocks(document.element.body, document):@@ -924,6 +1202,30 @@ def _roman(n: int) -> str:return out+def _list_number(n: int, fmt: str | None) -> str:+ fmt = fmt or ""+ if fmt == "none":+ return ""+ if fmt == "ordinal" and n >= 1:+ suffix = "th" if 11 <= n % 100 <= 13 else {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th")+ return f"{n}{suffix}"+ lower = fmt.startswith("lower")+ limit = 3999 if fmt.endswith("Roman") else 26 * 256 if fmt.endswith("Letter") else n+ if not (lower or fmt.startswith("upper")) or not 1 <= n <= limit:+ return f"0{n}" if fmt == "decimalZero" and 0 <= n < 10 else str(n)+ if fmt.endswith("Roman"):+ text = _roman(n)+ elif fmt.endswith("Alpha"):+ # CSS lower-alpha is bijective (z, aa, ab); Word's lowerLetter repeats (z, aa, bb).+ text = ""+ while n > 0:+ n, rest = divmod(n - 1, 26)+ text = chr(97 + rest) + text+ else:+ text = chr(97 + (n - 1) % 26) * ((n + 25) // 26)+ return text if lower else text.upper()++def _docx_mark_notes(document):"""Sentinels after body note references; the returned function labels the surviving ones (1, 2 / i, ii) and appends the notes."""from docx.opc.constants import RELATIONSHIP_TYPE as RTdiff --git a/studio/backend/tests/test_rag_parsing.py b/studio/backend/tests/test_rag_parsing.pyindex 9dbd3a97178..35197963b83 100644--- a/studio/backend/tests/test_rag_parsing.py+++ b/studio/backend/tests/test_rag_parsing.py@@ -442,6 +442,7 @@ def test_docx_table_vertical_merge_emitted_once(tmp_path):assert "SECTION | r0" in text and " | r1" in text and " | r2" in text+_W_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"_DOCX_XMLNS = ('xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ''xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" '@@ -869,6 +870,196 @@ def test_docx_numbers_visible_note_references_and_marks_the_body(tmp_path):)+def test_docx_keeps_list_numbers(tmp_path):+ document, docx, parsers = _shared_setup_1()+ document.add_paragraph("Lease terms")+ for clause in ("Rent is due on the first.", "Tenant pays utilities.", "No pets."):+ document.add_paragraph(clause, style = "List Number")+ path = tmp_path / "lease.docx"+ document.save(str(path))++ text = "\n".join(pg.text for pg in parsers.parse(str(path)))+ assert text == (+ "Lease terms\n1. Rent is due on the first.\n2. Tenant pays utilities.\n3. No pets."+ )+++def test_docx_keeps_multilevel_list_numbers(tmp_path):+ document, docx, parsers = _shared_setup_1()+ from docx.oxml import parse_xml++ levels = (("decimal", "%1."), ("decimal", "%1.%2"), ("lowerLetter", "(%3)"))+ document.part.numbering_part.element.append(+ parse_xml(+ f'<w:abstractNum {_DOCX_XMLNS} w:abstractNumId="90">'+ + "".join(+ f'<w:lvl w:ilvl="{i}"><w:start w:val="1"/><w:numFmt w:val="{fmt}"/>'+ f'<w:lvlText w:val="{text}"/></w:lvl>'+ for i, (fmt, text) in enumerate(levels)+ )+ + "</w:abstractNum>"+ )+ )+ document.part.numbering_part.element.append(+ parse_xml(f'<w:num {_DOCX_XMLNS} w:numId="90"><w:abstractNumId w:val="90"/></w:num>')+ )++ def item(level, text):+ return (+ f'<w:p {_DOCX_XMLNS}><w:pPr><w:numPr><w:ilvl w:val="{level}"/>'+ f'<w:numId w:val="90"/></w:numPr></w:pPr>{_r(text)}</w:p>'+ )++ section = document.element.body[-1]+ for level, clause in (+ (0, "Rent"),+ (1, "Amount"),+ (1, "Due date"),+ (2, "Weekdays"),+ (2, "Holidays"),+ (0, "Pets"),+ (1, "Dogs"),+ ):+ section.addprevious(parse_xml(item(level, clause)))+ path = tmp_path / "clauses.docx"+ document.save(str(path))++ text = "\n".join(pg.text for pg in parsers.parse(str(path)))+ assert text == (+ "1. Rent\n1.1 Amount\n1.2 Due date\n(a) Weekdays\n(b) Holidays\n2. Pets\n2.1 Dogs"+ )+++def test_docx_list_numbers_count_placeholders_and_survive_huge_starts(tmp_path):+ document, docx, parsers = _shared_setup_1()+ from docx.oxml import parse_xml++ numbering = document.part.numbering_part.element+ for num_id, start in ((91, "1"), (92, "9" * 4300)):+ numbering.append(+ parse_xml(+ f'<w:abstractNum {_DOCX_XMLNS} w:abstractNumId="{num_id}"><w:lvl w:ilvl="0">'+ f'<w:start w:val="{start}"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/>'+ "</w:lvl></w:abstractNum>"+ )+ )+ numbering.append(+ parse_xml(+ f'<w:num {_DOCX_XMLNS} w:numId="{num_id}"><w:abstractNumId w:val="{num_id}"/></w:num>'+ )+ )++ def item(num_id, text):+ return f'<w:p><w:pPr><w:numPr><w:numId w:val="{num_id}"/></w:numPr></w:pPr>{_r(text)}</w:p>'++ placeholder = (+ "<w:sdt><w:sdtPr><w:showingPlcHdr/></w:sdtPr>"+ f"<w:sdtContent>{item(91, 'Click here')}</w:sdtContent></w:sdt>"+ )+ body = (+ item(91, "First") + placeholder + item(91, "Third") + item(92, "Big") + item(92, "Bigger")+ )+ section = document.element.body[-1]+ for element in list(parse_xml(f"<w:body {_DOCX_XMLNS}>{body}</w:body>")):+ section.addprevious(element)+ path = tmp_path / "placeholder.docx"+ document.save(str(path))++ text = "\n".join(pg.text for pg in parsers.parse(str(path)))+ assert text.splitlines()[:2] == ["1. First", "3. Third"]+ assert text.splitlines()[-1].endswith(" Bigger")+++def test_docx_numbers_paragraphs_through_the_default_style(tmp_path):+ document, docx, parsers = _shared_setup_1()+ from docx.oxml import parse_xml++ number_style = document.styles["List Number"].element.find(f"{{{_W_NS}}}pPr/{{{_W_NS}}}numPr")+ normal = document.styles["Normal"].element+ p_pr = normal.find(f"{{{_W_NS}}}pPr")+ if p_pr is None:+ p_pr = parse_xml(f"<w:pPr {_DOCX_XMLNS}/>")+ normal.append(p_pr)+ p_pr.append(parse_xml(number_style.xml))+ document.add_paragraph("Rent")+ document.add_paragraph("Pets", style = "List Number")+ path = tmp_path / "default.docx"+ document.save(str(path))++ text = "\n".join(pg.text for pg in parsers.parse(str(path)))+ assert text == "1. Rent\n2. Pets"+++def test_docx_style_inherits_its_list_from_the_base_style(tmp_path):+ document, docx, parsers = _shared_setup_1()+ from docx.oxml import parse_xml++ numbering = document.part.numbering_part.element+ numbering.append(+ parse_xml(+ f'<w:abstractNum {_DOCX_XMLNS} w:abstractNumId="93">'+ '<w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/>'+ '<w:lvlText w:val="%1."/></w:lvl>'+ '<w:lvl w:ilvl="1"><w:start w:val="1"/><w:numFmt w:val="decimal"/>'+ '<w:lvlText w:val="%1.%2"/></w:lvl>'+ "</w:abstractNum>"+ )+ )+ numbering.append(+ parse_xml(f'<w:num {_DOCX_XMLNS} w:numId="93"><w:abstractNumId w:val="93"/></w:num>')+ )+ styles = document.styles.element+ for style_id, based_on, num_pr in (+ ("Clause1", "Normal", '<w:numId w:val="93"/>'),+ ("Clause2", "Clause1", '<w:ilvl w:val="1"/>'),+ ):+ styles.append(+ parse_xml(+ f'<w:style {_DOCX_XMLNS} w:type="paragraph" w:styleId="{style_id}">'+ f'<w:name w:val="{style_id}"/><w:basedOn w:val="{based_on}"/>'+ f"<w:pPr><w:numPr>{num_pr}</w:numPr></w:pPr></w:style>"+ )+ )+ for style, text in (+ ("Clause1", "Rent"),+ ("Clause2", "Amount"),+ ("Clause2", "Due date"),+ ("Clause1", "Pets"),+ ):+ document.add_paragraph(text, style = document.styles[style])+ path = tmp_path / "inherited.docx"+ document.save(str(path))++ text = "\n".join(pg.text for pg in parsers.parse(str(path)))+ assert text == "1. Rent\n1.1 Amount\n1.2 Due date\n2. Pets"+++def test_docx_with_unreadable_numbering_still_parses(tmp_path):+ import zipfile++ document, docx, parsers = _shared_setup_1()+ document.add_paragraph("Hello body")+ for clause in ("Rent", "Pets"):+ document.add_paragraph(clause, style = "List Number")+ source = tmp_path / "source.docx"+ document.save(str(source))+ path = tmp_path / "broken.docx"+ with zipfile.ZipFile(source) as src, zipfile.ZipFile(path, "w") as dst:+ for info in src.infolist():+ data = src.read(info)+ if info.filename == "word/numbering.xml":+ data = b"<w:numbering broken"+ elif info.filename == "[Content_Types].xml":+ data = data.replace(+ b"application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml",+ b"application/octet-stream",+ )+ dst.writestr(info, data)++ text = "\n".join(pg.text for pg in parsers.parse(str(path)))+ assert text == "Hello body\nRent\nPets"++def _parse_html(tmp_path, body):from core.rag import parsers@@ -902,6 +1093,31 @@ def test_html_block_elements_start_new_lines(tmp_path):assert text == "Install guide\nOne\nTwo items\nline one\nline two\ncell a | cell b"+def test_html_ordered_lists_keep_their_numbers(tmp_path):+ text = _parse_html(+ tmp_path,+ "<ol><li>Unplug</li><li>Wait<ul><li>Note</li></ul></li></ol><ol start=4><li>Plug in</ol>"+ '<ol type="a"><li>Left<li value=5>Right</ol><ol reversed><li>Three<li>Two<li>One</ol>',+ )+ assert text == (+ "1. Unplug\n2. Wait\nNote\n4. Plug in\na. Left\ne. Right\n3. Three\n2. Two\n1. One"+ )+++def test_html_list_numbers_stay_in_their_cell(tmp_path):+ text = _parse_html(tmp_path, '<table><tr><td><ol><li><img src="x"></td><td>B</td></tr></table>')+ assert text == "1. | B"+++def test_html_unclosed_lists_parse_in_linear_time(tmp_path):+ import time++ started = time.perf_counter()+ text = _parse_html(tmp_path, "<ol>" * 20000 + "x" + "</p>" * 20000)+ assert text == "x"+ assert time.perf_counter() - started < 3++def test_html_table_rows_keep_their_columns(tmp_path):text = _parse_html(tmp_path,diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.tsindex 5331216589e..6e839c40715 100644--- a/studio/frontend/scripts/check-bundle-budget.ts+++ b/studio/frontend/scripts/check-bundle-budget.ts@@ -127,8 +127,11 @@ export const BUDGET = {// Always allow on browser agent prompts (#13777) adds 91 B raw / 42 B transfer to the eager chat chunk// (6,770,922 -> 6,771,013 B raw, 2,035,640 -> 2,035,682 B transfer against cd947468f1, one machine and build,// Node 24, chunk count unchanged at 95), which put main 71 B raw over. Raised by that growth.- transferBytes: 2_035_705,- rawBytes: 6_771_033,+ // Word list numbering through the default style and basedOn (#13755) adds 228 B raw / 39 B transfer to the+ // eager attachment reader (6,770,962 -> 6,771,190 B raw, 2,035,676 -> 2,035,715 B transfer against 7ae1a5386,+ // one machine and build, Node 24, chunk count unchanged at 95). Raised by that growth.+ transferBytes: 2_035_744,+ rawBytes: 6_771_261,};// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering thediff --git a/studio/frontend/src/features/chat/attachment-content.ts b/studio/frontend/src/features/chat/attachment-content.tsindex 9cd9c39078e..029b485acc1 100644--- a/studio/frontend/src/features/chat/attachment-content.ts+++ b/studio/frontend/src/features/chat/attachment-content.ts@@ -1121,16 +1121,23 @@ function injectDocxListNumbers(archive: Uint8Array): Uint8Array {const nums = byId(numbering.root, n, "num", "numId");const styles = related("styles");const styleById = styles ? byId(styles.root, styles.w, "style", "styleId") : new Map<string, Element>();- const styleNumbering = new Map<string, Element | undefined>();- const styleNumPr = (id: string | undefined, depth = 0): Element | undefined => {+ const defaultStyle = [...styleById].find(+ ([, style]) => style.getAttributeNS(style.namespaceURI ?? "", "type") === "paragraph" &&+ ["1", "true", "on"].includes(style.getAttributeNS(style.namespaceURI ?? "", "default") ?? ""),+ )?.[0];+ // numId and ilvl inherit through basedOn independently, like any other paragraph property.+ const styleNumbering = new Map<string, string | undefined>();+ const styleNum = (id: string | undefined, name: "numId" | "ilvl", depth = 0): string | undefined => {if (id === undefined) return undefined;- if (styleNumbering.has(id)) return styleNumbering.get(id);+ const key = `${name}:${id}`;+ if (styleNumbering.has(key)) return styleNumbering.get(key);const style = styleById.get(id);if (!style || depth > 20) return undefined;const pPr = childElements(style, style.namespaceURI ?? "", "pPr")[0];- const numPr = (pPr && childElements(pPr, style.namespaceURI ?? "", "numPr")[0]) ?? styleNumPr(wordValue(style, "basedOn"), depth + 1);- styleNumbering.set(id, numPr);- return numPr;+ const numPr = pPr && childElements(pPr, style.namespaceURI ?? "", "numPr")[0];+ const value = wordValue(numPr, name) ?? styleNum(wordValue(style, "basedOn"), name, depth + 1);+ styleNumbering.set(key, value);+ return value;};type Level = { lvl?: Element; start: number; format?: string; restart?: string; legal: boolean; text: string };@@ -1147,9 +1154,9 @@ function injectDocxListNumbers(archive: Uint8Array): Uint8Array {const instances = new Map<string, Instance | undefined>();// A list defined through a numbering style (numStyleLink) takes its levels from that style's list.const linkedAbstract = (id: string, depth = 0): string => {- const numPr = styleNumPr(wordValue(abstracts.get(id), "numStyleLink"));- if (!numPr || depth > 5) return id;- const target = wordValue(nums.get(wordValue(numPr, "numId") ?? ""), "abstractNumId");+ const numId = styleNum(wordValue(abstracts.get(id), "numStyleLink"), "numId");+ if (numId === undefined || depth > 5) return id;+ const target = wordValue(nums.get(numId), "abstractNumId");return target === undefined || target === id ? id : linkedAbstract(target, depth + 1);};const instance = (numId: string): Instance | undefined => {@@ -1207,18 +1214,18 @@ function injectDocxListNumbers(archive: Uint8Array): Uint8Array {const mark = pPr && childElements(pPr, w, "rPr")[0];if (mark && (childElements(mark, w, "del").length || childElements(mark, w, "moveFrom").length)) return;const direct = pPr && childElements(pPr, w, "numPr")[0];- const styled = styleNumPr(wordValue(pPr, "pStyle"));- const numId = wordValue(direct, "numId") ?? wordValue(styled, "numId");+ const styleId = wordValue(pPr, "pStyle") ?? defaultStyle;+ const numId = wordValue(direct, "numId") ?? styleNum(styleId, "numId");const list = numId === undefined ? undefined : instance(numId);if (!list) return;const { abstractId, levels, restarts, byStyle } = list;// A heading style's numPr often names only the list; the level linked to its style supplies ilvl.let linked: number | undefined;- for (let style = wordValue(pPr, "pStyle"), depth = 0; style !== undefined && linked === undefined && depth <= 20; depth++) {+ for (let style = styleId, depth = 0; style !== undefined && linked === undefined && depth <= 20; depth++) {linked = byStyle.get(style);style = wordValue(styleById.get(style), "basedOn");}- const ilvl = Math.min(8, Math.max(0, Math.trunc(Number(wordValue(direct, "ilvl") ?? wordValue(styled, "ilvl") ?? linked ?? 0) || 0)));+ const ilvl = Math.min(8, Math.max(0, Math.trunc(Number(wordValue(direct, "ilvl") ?? styleNum(styleId, "ilvl") ?? linked ?? 0) || 0)));const { lvl, format, legal, text } = levels[ilvl];if (!lvl) return;// Word shares counters across instances of one abstract; a startOverride restarts them once.diff --git a/studio/frontend/tests/attachment-preview-text.test.ts b/studio/frontend/tests/attachment-preview-text.test.tsindex 3e0311859bf..c77e1e859cf 100644--- a/studio/frontend/tests/attachment-preview-text.test.ts+++ b/studio/frontend/tests/attachment-preview-text.test.ts@@ -1777,6 +1777,43 @@ test("Word heading styles linked to list levels number by their level", async ()}});+test("Word styles inherit their list and level through basedOn and the default style", async () => {+ const w = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"';+ const p = (text: string, style?: string) =>+ `<w:p>${style ? `<w:pPr><w:pStyle w:val="${style}"/></w:pPr>` : ""}<w:r><w:t>${text}</w:t></w:r></w:p>`;+ const style = (id: string, numPr: string, extra = "") =>+ `<w:style w:type="paragraph" w:styleId="${id}"${extra}><w:pPr><w:numPr>${numPr}</w:numPr></w:pPr></w:style>`;+ const bytes = zipSync({+ "[Content_Types].xml": strToU8("<Types/>"),+ "_rels/.rels": relationships([["officeDocument", "word/document.xml"]]),+ "word/_rels/document.xml.rels": relationships([["numbering", "numbering.xml"], ["styles", "styles.xml"]]),+ "word/document.xml": strToU8(+ `<w:document ${w}><w:body>${p("Rent", "Clause1")}${p("Amount", "Clause2")}${p("Due date", "Clause2")}${p("Pets", "Clause1")}${p("Plain")}</w:body></w:document>`,+ ),+ "word/numbering.xml": strToU8(+ `<w:numbering ${w}><w:abstractNum w:abstractNumId="1">` ++ '<w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/></w:lvl>' ++ '<w:lvl w:ilvl="1"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1.%2"/></w:lvl>' ++ '</w:abstractNum><w:num w:numId="1"><w:abstractNumId w:val="1"/></w:num></w:numbering>',+ ),+ "word/styles.xml": strToU8(+ `<w:styles ${w}>${style("Normal", '<w:numId w:val="1"/>', ' w:default="1"')}${style("Clause1", '<w:numId w:val="1"/>')}` ++ `<w:style w:type="paragraph" w:styleId="Clause2"><w:basedOn w:val="Clause1"/><w:pPr><w:numPr><w:ilvl w:val="1"/></w:numPr></w:pPr></w:style></w:styles>`,+ ),+ });+ const globals = globalThis as { DOMParser?: unknown; XMLSerializer?: unknown };+ const original = { DOMParser: globals.DOMParser, XMLSerializer: globals.XMLSerializer };+ globals.DOMParser = XmlDomParser;+ globals.XMLSerializer = XmlSerializer;+ try {+ const { default: mammoth } = await import("mammoth");+ const { value } = await mammoth.extractRawText({ buffer: Buffer.from(writeDocxListNumbers(bytes)) });+ assert.equal(value, "1. Rent\n\n1.1 Amount\n\n1.2 Due date\n\n2. Pets\n\n3. Plain\n\n");+ } finally {+ Object.assign(globals, original);+ }+});+test("a Word legal list reads every level as a decimal and skips unnumbered levels", async () => {const w = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"';const p = (text: string, ilvl: number) =>