Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

fix(text): markdown truncation pulls a mid-link cut back to before the link and the e2e scenario asserts the rune-cut contract (PIN-389)

Luigi Agosti2979f6d14ea0
diff --git a/docs/endpoints.md b/docs/endpoints.md
index 8fe32961..b10f3fa7 100644
--- a/docs/endpoints.md
+++ b/docs/endpoints.md
@@ -332,7 +332,8 @@ It reads the current frame scope's rendered HTML (the document `/html` returns),
so a `/frame`-selected iframe converts that frame. `format=text` returns the raw
Markdown body with `Content-Type: text/markdown; charset=utf-8`, and `maxChars`
keeps whole lines and rune-cuts the final overrunning one, never splitting a
-table row or link (those are dropped whole instead). When the
+table row (dropped whole) or a link (the cut pulls back to before the link). When
+the
converter yields nothing the response falls back to the raw page text and echoes
`extraction: "markdown_fallback"`.
diff --git a/internal/handlers/text.go b/internal/handlers/text.go
index 55df813d..30d013c5 100644
--- a/internal/handlers/text.go
+++ b/internal/handlers/text.go
@@ -312,12 +312,11 @@ func truncateChars(s string, limit int) (string, bool) {
}
// truncateCharsLine cuts s to at most limit characters, keeping whole lines
-// while they fit and then rune-cutting the first line that overruns. The partial
-// line is dropped instead of cut only for the two shapes a mid-line cut would
-// corrupt: a Markdown table row (starts with '|') or a cut that would land inside
-// a [..](..) link — so a cut never splits a table row or link. Reports whether it
-// cut. This differs from truncateChars, which cuts at the exact rune regardless
-// of line structure.
+// while they fit and then rune-cutting the first line that overruns. A cut never
+// splits a Markdown table row or link: a table row (starts with '|') that does
+// not fit is dropped whole, and a cut that would land inside a [..](..) link is
+// pulled back to before the link. Reports whether it cut. This differs from
+// truncateChars, which cuts at the exact rune regardless of line structure.
func truncateCharsLine(s string, limit int) (string, bool) {
if limit < 0 || utf8.RuneCountInString(s) <= limit {
return s, false
@@ -358,9 +357,11 @@ func truncateCharsLine(s string, limit int) (string, bool) {
// cut through one.
var markdownLinkRe = regexp.MustCompile(`\[[^\]]*\]\([^)]*\)`)
-// cutLineForMarkdown returns the first budget runes of line for use as the final
-// partial line of a truncation. ok is false when that cut would fall inside a
-// [..](..) link, which must not be split; the caller then drops the line whole.
+// cutLineForMarkdown returns the leading runes of line (at most budget) for use
+// as the final partial line of a truncation. A cut that would fall inside a
+// [..](..) link is pulled back to the link's start so no half-open link escapes,
+// then trailing whitespace is trimmed. ok is false only when nothing survives —
+// the line began with the link that the budget split.
func cutLineForMarkdown(line string, budget int) (string, bool) {
cut := len(line)
count := 0
@@ -373,10 +374,15 @@ func cutLineForMarkdown(line string, budget int) (string, bool) {
}
for _, loc := range markdownLinkRe.FindAllStringIndex(line, -1) {
if loc[0] < cut && cut < loc[1] {
- return "", false
+ cut = loc[0]
+ break
}
}
- return line[:cut], true
+ partial := strings.TrimRight(line[:cut], " \t")
+ if partial == "" {
+ return "", false
+ }
+ return partial, true
}
// writeTextResponse truncates, IDPI-scans, and writes the document text as
diff --git a/internal/handlers/text_test.go b/internal/handlers/text_test.go
index cd240f35..1da3f7d5 100644
--- a/internal/handlers/text_test.go
+++ b/internal/handlers/text_test.go
@@ -528,21 +528,53 @@ func TestTruncateCharsLine_RuneCutsLongFirstLine(t *testing.T) {
}
}
-// A cut that would land inside a [..](..) link drops the whole line rather than
-// emit a half-open link; the fitting heading before it survives.
+// A cut that would land inside a [..](..) link is pulled back to before the
+// link, never emitting a half-open one — and the text before the link survives
+// rather than the whole line being dropped.
func TestTruncateCharsLine_NeverSplitsLink(t *testing.T) {
- line2 := "Read [the annual report](https://example.com/reports/2026/annual.pdf) today"
- body := "# Title\n" + line2
- cut, truncated := truncateCharsLine(body, 30) // budget lands inside the link text
- if !truncated {
- t.Fatal("expected a cut")
- }
- if cut != "# Title" {
- t.Fatalf("a mid-link cut must drop the line, keeping only the heading; got %q", cut)
- }
- if strings.Contains(cut, "](") || strings.Count(cut, "[") != strings.Count(cut, "]") {
- t.Fatalf("a partial link survived: %q", cut)
+ assertNoPartialLink := func(t *testing.T, cut string) {
+ t.Helper()
+ if strings.Contains(cut, "](") || strings.Count(cut, "[") != strings.Count(cut, "]") {
+ t.Fatalf("a partial link survived: %q", cut)
+ }
}
+
+ t.Run("cut pulls back to before the link, keeping the lead", func(t *testing.T) {
+ line2 := "Read [the annual report](https://example.com/reports/2026/annual.pdf) today"
+ body := "# Title\n" + line2
+ cut, truncated := truncateCharsLine(body, 30) // budget lands inside the link
+ if !truncated {
+ t.Fatal("expected a cut")
+ }
+ if cut != "# Title\nRead" {
+ t.Fatalf("expected the lead before the link to survive; got %q", cut)
+ }
+ assertNoPartialLink(t, cut)
+ })
+
+ // A long opening paragraph with an inline link across the limit must still
+ // return the prose before the link, not an empty body.
+ t.Run("long first line with a link across the limit", func(t *testing.T) {
+ lead := strings.Repeat("word ", 38) // 190 chars, trailing space
+ body := lead + "[annual report](https://example.com/x/y/z) and more padding text here"
+ cut, truncated := truncateCharsLine(body, 200) // budget lands inside the link
+ if !truncated {
+ t.Fatal("expected a cut")
+ }
+ if cut == "" {
+ t.Fatal("a long first paragraph with a link must return the prose before it, not empty")
+ }
+ if strings.Contains(cut, "[") {
+ t.Fatalf("the cut must end before the link's '['; got %q", cut)
+ }
+ if !strings.HasPrefix(body, cut) {
+ t.Fatalf("the partial line must be a prefix of the source; got %q", cut)
+ }
+ if n := utf8.RuneCountInString(cut); n > 200 {
+ t.Fatalf("cut kept %d chars, over the 200 limit", n)
+ }
+ assertNoPartialLink(t, cut)
+ })
}
func TestTruncateCharsLine_NoCutWhenUnderLimit(t *testing.T) {
diff --git a/tests/e2e/scenarios/api/text-markdown-basic.sh b/tests/e2e/scenarios/api/text-markdown-basic.sh
index e88fe488..350f2192 100755
--- a/tests/e2e/scenarios/api/text-markdown-basic.sh
+++ b/tests/e2e/scenarios/api/text-markdown-basic.sh
@@ -59,20 +59,46 @@ pt_get "/text?mode=markdown&maxChars=120"
assert_ok "text markdown maxChars=120"
assert_json_eq "$RESULT" '.truncated' 'true' "response marked truncated"
-# The last line must be whole: no dangling half of a table row or link. Every
-# returned line has to appear verbatim in the untruncated body.
+# Truncation rule: whole lines are kept, the final overrunning line is a rune-cut
+# prefix, a table row is dropped whole, and a cut pulls back to before a [..](..)
+# link. Assert every line but the last is a whole source line; the last is a
+# prefix of some source line; no returned line is a partial table row; and the
+# result leaves no link half-open.
FULL=$(pt_get "/text?mode=markdown" >/dev/null; echo "$RESULT" | jq -r '.text')
CUT=$(pt_get "/text?mode=markdown&maxChars=120" >/dev/null; echo "$RESULT" | jq -r '.text')
-PARTIAL_LINE=0
-while IFS= read -r line; do
+CUT_LINES=()
+while IFS= read -r line; do CUT_LINES+=("$line"); done <<<"$CUT"
+LAST_IDX=$(( ${#CUT_LINES[@]} - 1 ))
+LINE_RULE_OK=1
+for i in "${!CUT_LINES[@]}"; do
+ line="${CUT_LINES[$i]}"
[ -z "$line" ] && continue
- if ! grep -Fqx -- "$line" <<<"$FULL"; then
- PARTIAL_LINE=1
- echo -e " ${RED}✗${NC} line not whole: $line"
+ if [ "$i" -lt "$LAST_IDX" ]; then
+ if ! grep -Fqx -- "$line" <<<"$FULL"; then
+ LINE_RULE_OK=0; echo -e " ${RED}✗${NC} non-final line not whole: $line"
+ fi
+ else
+ PREFIX_OK=0
+ while IFS= read -r fline; do
+ case "$fline" in "$line"*) PREFIX_OK=1; break;; esac
+ done <<<"$FULL"
+ if [ "$PREFIX_OK" -eq 0 ]; then
+ LINE_RULE_OK=0; echo -e " ${RED}✗${NC} final line is not a prefix of any source line: $line"
+ fi
fi
-done <<<"$CUT"
-if [ "$PARTIAL_LINE" -eq 0 ]; then
- echo -e " ${GREEN}✓${NC} every truncated line is a complete source line"
+ case "$line" in
+ "|"*) grep -Fqx -- "$line" <<<"$FULL" || { LINE_RULE_OK=0; echo -e " ${RED}✗${NC} partial table row: $line"; } ;;
+ esac
+done
+# No half-open link anywhere in the result: brackets balance and every "](" has a
+# closing ")".
+OPEN=$(tr -cd '[' <<<"$CUT" | wc -c); CLOSE=$(tr -cd ']' <<<"$CUT" | wc -c)
+LOPEN=$(grep -o '](' <<<"$CUT" | wc -l); RPAREN=$(tr -cd ')' <<<"$CUT" | wc -c)
+if [ "$OPEN" -ne "$CLOSE" ] || [ "$LOPEN" -gt "$RPAREN" ]; then
+ LINE_RULE_OK=0; echo -e " ${RED}✗${NC} unbalanced link markup: [=$OPEN ]=$CLOSE ](=$LOPEN )=$RPAREN"
+fi
+if [ "$LINE_RULE_OK" -eq 1 ]; then
+ echo -e " ${GREEN}✓${NC} truncated lines obey the cut rule (whole lines, prefix last line, no split row or link)"
((ASSERTIONS_PASSED++)) || true
else
((ASSERTIONS_FAILED++)) || true