The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(signal): fence realigned tables so the code-block pass owns every MONOSPACE range
Tekniumd6f954f51010
diff --git a/gateway/platforms/signal_format.py b/gateway/platforms/signal_format.pyindex 3a22b7ce309..bce94565541 100644--- a/gateway/platforms/signal_format.py+++ b/gateway/platforms/signal_format.py@@ -36,43 +36,43 @@ def _normalize_bullet_markers(source: str) -> str:for idx, part in enumerate(parts))-def _realign_tables(text: str, styles: list[tuple[int, int, str]]) -> str:- """Detect GFM table blocks and re-align each to a fixed monospace width, recording a- MONOSPACE style range over the rendered block. Runs after code-block extraction, so no- fenced regions remain to skip."""+def _fence_tables(source: str) -> str:+ """Re-align every GFM table outside a code fence and wrap it in a fence, so the code-block pass+ in markdown_to_signal() records one MONOSPACE range over the aligned block and shifts every+ later range for it. Fenced regions are left alone: a pipe table inside a code block is code."""+ parts = re.split(r"(```.*?```)", source, flags=re.DOTALL)+ return "".join(part if idx % 2 else _fence_unfenced_tables(part) for idx, part in enumerate(parts))+++def _fence_unfenced_tables(text: str) -> str:if "|" not in text:return text- lines = text.split("\n")- result_lines: list[str] = []+ lines, out = text.split("\n"), []i, n = 0, len(lines)while i < n:- line = lines[i]- if "|" in line and i + 1 < n and is_table_divider(lines[i + 1]):+ # Same block rule as realign_markdown_tables(): header row, divider, contiguous pipe rows.+ if "|" in lines[i] and i + 1 < n and is_table_divider(lines[i + 1]):j = i + 2while j < n and "|" in lines[j] and lines[j].strip():j += 1- rendered = realign_markdown_tables("\n".join(lines[i:j]), _TABLE_WIDTH)- block_start = sum(len(rl) + 1 for rl in result_lines)- styles.append((block_start, len(rendered), "MONOSPACE"))- result_lines.extend(rendered.split("\n"))+ out += ["```", realign_markdown_tables("\n".join(lines[i:j]), _TABLE_WIDTH), "```"]i = jcontinue- result_lines.append(line)+ out.append(lines[i])i += 1- return "\n".join(result_lines)+ return "\n".join(out)def markdown_to_signal(text: str) -> tuple[str, list[str]]:"""Convert markdown to plain text + Signal textStyles list. Signal uses ``bodyRanges`` (signal-cli``textStyle`` / ``textStyles`` params) as ``start:length:STYLE`` with positions in UTF-16 code units.Supported styles: BOLD, ITALIC, STRIKETHROUGH, MONOSPACE."""- text = _normalize_bullet_markers(re.sub(r"\n{3,}", "\n\n", text).strip())+ text = _fence_tables(_normalize_bullet_markers(re.sub(r"\n{3,}", "\n\n", text).strip()))styles: list[tuple[int, int, str]] = []while match := _CODE_BLOCK_RE.search(text):inner = match.group(1).rstrip("\n")styles.append((match.start(), len(inner), "MONOSPACE"))text = text[: match.start()] + inner + text[match.end() :]- text = _realign_tables(text, styles)new_text, last_end = "", 0for match in _HEADING_RE.finditer(text):new_text += text[last_end : match.start()]diff --git a/tests/gateway/test_signal_format.py b/tests/gateway/test_signal_format.pyindex dbc355a704c..0be7e64cf3b 100644--- a/tests/gateway/test_signal_format.py+++ b/tests/gateway/test_signal_format.py@@ -242,37 +242,35 @@ class TestTableRealignment:"""GFM pipe tables are re-aligned to a fixed monospace width and wrapped in asingle MONOSPACE style range, per the Signal table-rendering feature request."""- def test_table_becomes_single_monospace_block(self):- md = "| Name | Age |\n|------|-----|\n| Alice | 30 |\n| Bob | 25 |"- text, styles = _m2s(md)- mono = _find_style(styles, "MONOSPACE")- assert len(mono) == 1- start, length = (int(p) for p in mono[0].split(":")[:2])- block = text[start : start + length]+ @staticmethod+ def _u16_slice(text: str, style: str) -> str:+ start, length = (int(p) for p in style.split(":")[:2])+ u16 = text.encode("utf-16-le")+ return u16[start * 2 : (start + length) * 2].decode("utf-16-le")++ def test_wide_char_table_becomes_one_aligned_monospace_block(self):+ """Cells with CJK/emoji (2 display cells, 1-2 UTF-16 units) still produce pipes that line up+ by display width, one MONOSPACE range covering exactly the block, and correct UTF-16 offsets+ for styles after it."""+ from wcwidth import wcswidth++ text, styles = _m2s("| 名前 | Score |\n|---|---|\n| 東京 | 🚀 |\n| Bob | 1 |\n\n**tail**")+ (mono,) = _find_style(styles, "MONOSPACE")+ block = self._u16_slice(text, mono)+ assert text == block + "\n\ntail"rows = block.split("\n")- assert len(rows) == 4- # Realignment pads cells so every '|' lines up across header/divider/body,- # even though the source rows ("Alice" vs "Bob") had different widths.- pipe_offsets = [i for i, ch in enumerate(rows[0]) if ch == "|"]- assert all([i for i, ch in enumerate(row) if ch == "|"] == pipe_offsets for row in rows[1:])-- def test_non_table_pipes_left_alone(self):- """A lone '|' with no divider row is not a table and must not be touched."""- text, styles = _m2s("cost | value\nnot a table")- assert text == "cost | value\nnot a table"- assert _find_style(styles, "MONOSPACE") == []-- def test_table_surrounded_by_prose_keeps_prose_out_of_monospace(self):- md = "Before.\n\n| A | B |\n|---|---|\n| 1 | 2 |\n\nAfter."- text, styles = _m2s(md)- assert text.startswith("Before.\n\n")- assert text.endswith("\n\nAfter.")+ assert len(rows) == 4 and all(wcswidth(row) == wcswidth(rows[0]) for row in rows)+ assert self._u16_slice(text, _find_style(styles, "BOLD")[0]) == "tail"++ def test_fenced_pipe_table_is_code_and_later_code_range_survives_realignment(self):+ """A pipe table inside ``` is code and must not be realigned or double-styled; a table's+ padding changes its length, and a code block after it still maps to its own text."""+ text, styles = _m2s("| Name | Age |\n|---|---|\n| Alice | 30 |\n\n```\n| a | b |\n|---|---|\n| 1 | 22 |\n```")mono = _find_style(styles, "MONOSPACE")- assert len(mono) == 1- start, length = (int(p) for p in mono[0].split(":")[:2])- block = text[start : start + length]- assert "Before" not in block and "After" not in block- assert block.startswith("| A")+ assert len(mono) == 2+ assert self._u16_slice(text, mono[0]) == "| Name | Age |\n|-------|-----|\n| Alice | 30 |"+ assert self._u16_slice(text, mono[1]) == "| a | b |\n|---|---|\n| 1 | 22 |"+ assert "cost | value" == _m2s("cost | value\nnot a table")[0].split("\n")[0]class TestSignalStreamingPatch: