feat(signal): render markdown tables as monospace-aligned blocks

markdown_to_signal() passed GFM tables through untouched, so Signal's
proportional font left columns unaligned. Detect table blocks after
code-block extraction, re-align them with realign_markdown_tables(),
and cover each rendered block with a single MONOSPACE style range.

Fixes #106181
This commit is contained in:
chelsealong
2026-09-09 02:25:11 +00:00
committed by Teknium
parent 6494163911
commit 0edc47debf
2 changed files with 71 additions and 0 deletions
+34
View File
@@ -5,6 +5,13 @@ from __future__ import annotations
import re
from agent.markdown_tables import is_table_divider, realign_markdown_tables
# Signal has no fixed-width client area; this budgets for a phone screen in the app's
# monospace face. Tables wider than this fall back to realign_markdown_tables()'s
# vertical Key: value rendering rather than soft-wrapping mid-cell.
_TABLE_WIDTH = 40
_CODE_BLOCK_RE = re.compile(r"```[a-zA-Z0-9_+-]*\n?(.*?)```", re.DOTALL)
_HEADING_RE = re.compile(r"^#{1,6}\s+", re.MULTILINE)
_INLINE_PATTERNS = [
@@ -29,6 +36,32 @@ 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."""
if "|" not in text:
return text
lines = text.split("\n")
result_lines: list[str] = []
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]):
j = i + 2
while 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"))
i = j
continue
result_lines.append(line)
i += 1
return "\n".join(result_lines)
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.
@@ -39,6 +72,7 @@ def markdown_to_signal(text: str) -> tuple[str, list[str]]:
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 = "", 0
for match in _HEADING_RE.finditer(text):
new_text += text[last_end : match.start()]
+37
View File
@@ -238,6 +238,43 @@ class TestMarkdownStripPatch:
# signal-streaming-patch: SUPPORTS_MESSAGE_EDITING and send() behavior
# ===========================================================================
class TestTableRealignment:
"""GFM pipe tables are re-aligned to a fixed monospace width and wrapped in a
single 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]
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.")
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")
class TestSignalStreamingPatch:
"""Tests for signal-streaming-patch: cursor suppression and edit support.