Skip to content

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

feat(text): add mode=markdown to /text so one page returns Markdown through the seaportal converter (PIN-389)

Luigi Agosti8e13c0ae6e6e
diff --git a/docs/endpoints.md b/docs/endpoints.md
index 75f2d68c..814c9ea8 100644
--- a/docs/endpoints.md
+++ b/docs/endpoints.md
@@ -315,7 +315,7 @@ Snapshot query parameters:
Text query parameters:
-- `mode=raw` (`mode=full` is an alias; any other value is a 400 naming the accepted ones)
+- `mode=raw` (`mode=full` is an alias), `mode=markdown` (any other value is a 400 naming the accepted ones)
- `format`
- `maxChars`
- `frameId`
@@ -325,6 +325,16 @@ Text query parameters:
full `innerText`, or `/snapshot` for structured UI text like prices and button
labels.
+`mode=markdown` returns the rendered page as Markdown through the seaportal
+converter — the same conversion the site scraper applies — with the JSON
+envelope carrying the converter's `title` and `description` alongside `text`.
+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`
+truncates on a line boundary so a cut never splits a table row or link. When the
+converter yields nothing the response falls back to the raw page text and echoes
+`extraction: "markdown_fallback"`.
+
`mode=raw` and `mode=full` are the same extraction — the whole unfiltered page —
and are what the CLI's `--raw` and `--full` send. The default extraction keeps
block and table-cell boundaries: adjacent cells are separated by a tab and
diff --git a/internal/handlers/text.go b/internal/handlers/text.go
index 92702b3c..cacae21d 100644
--- a/internal/handlers/text.go
+++ b/internal/handlers/text.go
@@ -16,11 +16,13 @@ import (
"github.com/pinchtab/pinchtab/internal/browsers"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/httpx"
+ "github.com/pinchtab/pinchtab/internal/scrape"
"github.com/pinchtab/pinchtab/internal/selector"
"unicode/utf8"
)
// @Endpoint GET /text
+// @Param mode string query Extraction mode: "" default Readability, "raw"/"full" whole-page innerText, "markdown" seaportal Markdown of the rendered page (falls back to raw text as "markdown_fallback" when the converter yields nothing); any other value is a 400 (optional)
func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {
tabID := r.URL.Query().Get("tabId")
effectiveCfg, textRoute, ok := h.resolveReadRouting(w, r, tabID, "text", browsers.ShapeRenderedRead)
@@ -136,9 +138,10 @@ const rawTextScript = `document.body.innerText`
// to readability, so a caller who read the CLI help and wrote ?mode=full against the
// API got the filtered output while believing they had asked for innerText.
var textModes = map[string]string{
- "": "",
- "raw": "raw",
- "full": "raw",
+ "": "",
+ "raw": "raw",
+ "full": "raw",
+ "markdown": "markdown",
}
// resolveTextMode maps a requested mode onto the extraction that runs, and REFUSES an
@@ -172,8 +175,18 @@ const (
extractionReadability = "readability"
extractionRaw = "raw"
extractionReadabilityFallback = "readability_fallback"
+ extractionMarkdown = "markdown"
+ extractionMarkdownFallback = "markdown_fallback"
)
+// isMarkdownExtraction reports whether an extraction came from the markdown
+// mode, so the writer serves text/markdown and truncates on line boundaries.
+// The fallback is included: the caller asked for markdown, and raw text is
+// still valid Markdown.
+func isMarkdownExtraction(mode string) bool {
+ return mode == extractionMarkdown || mode == extractionMarkdownFallback
+}
+
// Readability is an article heuristic; on a layout it does not recognise as an
// article (landing page, dashboard, docs index) it returns the single block it
// scored highest. Measured against document.body.innerText, a collapse retains
@@ -193,10 +206,12 @@ const headerTextExtraction = "X-PT-Text-Extraction"
// the mode that actually ran and the length of the raw document it was measured
// against (RawKnown is false when the baseline extraction itself failed).
type textExtraction struct {
- Text string
- Mode string
- RawLength int
- RawKnown bool
+ Text string
+ Mode string
+ RawLength int
+ RawKnown bool
+ Title string
+ Description string
}
// extractDocumentText reads the document's text (readability unless mode=="raw")
@@ -204,6 +219,9 @@ type textExtraction struct {
// output that covers too little of the raw document is discarded in favour of
// the raw text, reported as extractionReadabilityFallback.
func (h *Handlers) extractDocumentText(tCtx context.Context, mode, targetFrameID string) (textExtraction, error) {
+ if mode == extractionMarkdown {
+ return h.extractDocumentMarkdown(tCtx, targetFrameID)
+ }
if mode == "raw" {
text, err := h.extractText(tCtx, rawTextScript, targetFrameID)
if err != nil {
@@ -228,6 +246,38 @@ func (h *Handlers) extractDocumentText(tCtx context.Context, mode, targetFrameID
return textExtraction{Text: text, Mode: extractionReadability, RawLength: rawLen, RawKnown: true}, nil
}
+// extractDocumentMarkdown converts the frame-scoped rendered document to
+// Markdown through the shared seaportal helper, reusing the same HTML read the
+// /html inspect path uses so the frame scope is honoured identically. An empty
+// conversion falls back to the raw document text, echoed as markdown_fallback.
+func (h *Handlers) extractDocumentMarkdown(tCtx context.Context, targetFrameID string) (textExtraction, error) {
+ payload, err := h.inspectDocument(tCtx, targetFrameID, inspectKindHTML)
+ if err != nil {
+ return textExtraction{}, err
+ }
+ md := scrape.ToMarkdown(payload.HTML, payload.URL)
+ if md.Markdown == "" {
+ raw, rawErr := h.extractText(tCtx, rawTextScript, targetFrameID)
+ if rawErr != nil {
+ return textExtraction{}, rawErr
+ }
+ return textExtraction{
+ Text: raw,
+ Mode: extractionMarkdownFallback,
+ RawLength: utf8.RuneCountInString(raw),
+ RawKnown: true,
+ Title: md.Title,
+ Description: md.Description,
+ }, nil
+ }
+ return textExtraction{
+ Text: md.Markdown,
+ Mode: extractionMarkdown,
+ Title: md.Title,
+ Description: md.Description,
+ }, nil
+}
+
func readabilityCollapsed(extractedLen, rawLen int) bool {
return rawLen >= readabilityCoverageFloorChars && float64(extractedLen) < float64(rawLen)*readabilityCoverageRatio
}
@@ -260,17 +310,52 @@ func truncateChars(s string, limit int) (string, bool) {
return s, false
}
+// truncateCharsLine cuts s to at most limit characters on a line boundary, so a
+// cut never lands inside a Markdown table row or link. It keeps whole lines
+// while they fit and drops the rest; when the first line alone exceeds the limit
+// the result is empty. Reports whether it cut. This differs from truncateChars,
+// which cuts at the exact rune.
+func truncateCharsLine(s string, limit int) (string, bool) {
+ if limit < 0 || utf8.RuneCountInString(s) <= limit {
+ return s, false
+ }
+ var b strings.Builder
+ count := 0
+ for i, line := range strings.Split(s, "\n") {
+ add := utf8.RuneCountInString(line)
+ if i > 0 {
+ add++ // the newline joining this line to the previous
+ }
+ if count+add > limit {
+ break
+ }
+ if i > 0 {
+ b.WriteByte('\n')
+ }
+ b.WriteString(line)
+ count += add
+ }
+ return b.String(), true
+}
+
// writeTextResponse truncates, IDPI-scans, and writes the document text as
// plain text (format text/plain) or the JSON envelope.
func (h *Handlers) writeTextResponse(w http.ResponseWriter, r *http.Request, tCtx context.Context, extraction textExtraction, maxChars int, format string, route *browserops.RouteMetadata, scope *frameDisclosure) {
text := extraction.Text
truncated := false
if maxChars > -1 {
- text, truncated = truncateChars(text, maxChars)
+ if isMarkdownExtraction(extraction.Mode) {
+ text, truncated = truncateCharsLine(text, maxChars)
+ } else {
+ text, truncated = truncateChars(text, maxChars)
+ }
}
url, _ := h.Bridge.CurrentURL(tCtx)
title, _ := h.Bridge.CurrentTitle(tCtx)
+ if extraction.Title != "" {
+ title = extraction.Title
+ }
h.recordResolvedURL(r, url)
// IDPI: scan extracted text for injection patterns and optionally wrap.
@@ -284,7 +369,11 @@ func (h *Handlers) writeTextResponse(w http.ResponseWriter, r *http.Request, tCt
w.Header().Set(headerTextExtraction, extraction.Mode)
if format == "text" || format == "plain" {
- w.Header().Set("Content-Type", "text/plain; charset=utf-8")
+ contentType := "text/plain; charset=utf-8"
+ if isMarkdownExtraction(extraction.Mode) {
+ contentType = "text/markdown; charset=utf-8"
+ }
+ w.Header().Set("Content-Type", contentType)
w.WriteHeader(200)
_, _ = w.Write([]byte(text))
return
@@ -302,6 +391,9 @@ func (h *Handlers) writeTextResponse(w http.ResponseWriter, r *http.Request, tCt
if extraction.RawKnown {
resp["rawLength"] = extraction.RawLength
}
+ if extraction.Description != "" {
+ resp["description"] = extraction.Description
+ }
if result.Warning != "" {
resp["idpiWarning"] = result.Warning
}
@@ -309,6 +401,7 @@ func (h *Handlers) writeTextResponse(w http.ResponseWriter, r *http.Request, tCt
}
// @Endpoint GET /tabs/{id}/text
+// @Param mode string query Extraction mode: "" default Readability, "raw"/"full" whole-page innerText, "markdown" seaportal Markdown of the rendered page (falls back to raw text as "markdown_fallback" when the converter yields nothing); any other value is a 400 (optional)
func (h *Handlers) HandleTabText(w http.ResponseWriter, r *http.Request) {
h.withPathTabID(w, r, h.HandleText)
}
diff --git a/internal/handlers/text_test.go b/internal/handlers/text_test.go
index a828dfd3..70b901ef 100644
--- a/internal/handlers/text_test.go
+++ b/internal/handlers/text_test.go
@@ -155,6 +155,9 @@ func TestResolveTextMode(t *testing.T) {
{"full", "raw"},
{"FULL", "raw"},
{" raw ", "raw"},
+ {"markdown", "markdown"},
+ {"MARKDOWN", "markdown"},
+ {" markdown ", "markdown"},
} {
got, err := resolveTextMode(tc.requested)
if err != nil {
@@ -176,12 +179,12 @@ func TestResolveTextMode_RefusesAnUnimplementedMode(t *testing.T) {
if !strings.Contains(message, `"readable"`) {
t.Errorf("the refusal does not name what the caller sent: %s", message)
}
- for _, accepted := range []string{"full", "raw"} {
+ for _, accepted := range []string{"full", "markdown", "raw"} {
if !strings.Contains(message, accepted) {
t.Errorf("the refusal does not name the accepted value %q: %s", accepted, message)
}
}
- if !strings.Contains(message, "full, raw") {
+ if !strings.Contains(message, "full, markdown, raw") {
t.Errorf("the accepted values are not in a stable order, so the refusal differs between runs: %s", message)
}
}
@@ -390,3 +393,214 @@ func TestExtractDocumentText_CoverageFloorCountsCharactersNotBytes(t *testing.T)
t.Fatalf("RawLength = %d, want %d characters", extraction.RawLength, utf8.RuneCountInString(raw))
}
}
+
+// markdownFixtureHTML is a rendered article the seaportal converter turns into
+// Markdown: a heading, two subheadings, an inline link, a list and a 3-column
+// table, with enough prose that extraction does not treat it as thin.
+const markdownFixtureHTML = `<!doctype html><html><head><title>Doc Title</title>` +
+ `<meta name="description" content="A short description of the doc."></head><body><article>` +
+ `<h1>Main Heading</h1>` +
+ `<h2>First Section</h2>` +
+ `<p>A paragraph with an <a href="https://example.com/link">inline link</a> in it that keeps ` +
+ `going with more words so extraction triggers properly and does not collapse to nothing.</p>` +
+ `<h2>Second Section</h2>` +
+ `<ul><li>Alpha item one here</li><li>Beta item two here</li><li>Gamma item three here</li></ul>` +
+ `<table><thead><tr><th>Col A</th><th>Col B</th><th>Col C</th></tr></thead>` +
+ `<tbody><tr><td>a1</td><td>b1</td><td>c1</td></tr><tr><td>a2</td><td>b2</td><td>c2</td></tr></tbody></table>` +
+ `<p>More trailing text so the article body sits comfortably above any thin-content threshold ` +
+ `the extractor applies before it will hand back a document.</p></article></body></html>`
+
+// markdownBridge answers the frame-scoped HTML inspect read with a fixed
+// document and the raw-text script with fixed text, so the markdown extraction
+// path can be exercised without a real browser.
+type markdownBridge struct {
+ mockBridge
+ html string
+ url string
+ raw string
+}
+
+func (b *markdownBridge) EvaluateInFrame(_ context.Context, _ string, _ string, result any, _ bridge.EvalOpts) error {
+ switch out := result.(type) {
+ case *inspectPayload:
+ out.HTML = b.html
+ out.URL = b.url
+ return nil
+ case *string:
+ *out = b.raw
+ return nil
+ default:
+ return fmt.Errorf("evaluate result is %T, want *inspectPayload or *string", result)
+ }
+}
+
+func TestExtractDocumentMarkdown_ConvertsRenderedHTMLToMarkdown(t *testing.T) {
+ b := &markdownBridge{html: markdownFixtureHTML, url: "http://example.test/page"}
+ h := New(b, &config.RuntimeConfig{}, nil, nil, nil)
+
+ extraction, err := h.extractDocumentText(context.Background(), extractionMarkdown, "FRAME1")
+ if err != nil {
+ t.Fatalf("extractDocumentText: %v", err)
+ }
+ if extraction.Mode != extractionMarkdown {
+ t.Fatalf("Mode = %q, want %q", extraction.Mode, extractionMarkdown)
+ }
+ if extraction.Title != "Doc Title" {
+ t.Errorf("Title = %q, want the converter title", extraction.Title)
+ }
+ if extraction.Description != "A short description of the doc." {
+ t.Errorf("Description = %q, want the converter description", extraction.Description)
+ }
+ for _, syntax := range []string{"# ", "## ", "[inline link](https://example.com/link)", "- Alpha item one here", "|"} {
+ if !strings.Contains(extraction.Text, syntax) {
+ t.Errorf("markdown does not contain %q:\n%s", syntax, extraction.Text)
+ }
+ }
+ if extraction.RawKnown {
+ t.Errorf("RawKnown = true; markdown has no raw-length comparison to report")
+ }
+}
+
+func TestExtractDocumentMarkdown_EmptyConversionFallsBackToRaw(t *testing.T) {
+ b := &markdownBridge{html: "<html><body></body></html>", url: "http://example.test/empty", raw: landingPageRawText}
+ h := New(b, &config.RuntimeConfig{}, nil, nil, nil)
+
+ extraction, err := h.extractDocumentText(context.Background(), extractionMarkdown, "FRAME1")
+ if err != nil {
+ t.Fatalf("extractDocumentText: %v", err)
+ }
+ if extraction.Mode != extractionMarkdownFallback {
+ t.Fatalf("Mode = %q, want %q when the converter yields nothing", extraction.Mode, extractionMarkdownFallback)
+ }
+ if extraction.Text != landingPageRawText {
+ t.Errorf("Text = %q, want the raw document text", extraction.Text)
+ }
+ if !extraction.RawKnown || extraction.RawLength != utf8.RuneCountInString(landingPageRawText) {
+ t.Errorf("RawLength = %d (known=%v), want %d", extraction.RawLength, extraction.RawKnown, utf8.RuneCountInString(landingPageRawText))
+ }
+}
+
+// The markdown table proves the guarantee: a cut inside a row would split a
+// pipe-delimited line, so every returned line must be whole.
+func TestTruncateCharsLine_NeverCutsMidLine(t *testing.T) {
+ body := "| Col A | Col B | Col C |\n|-------|-------|-------|\n| a1 | b1 | c1 |\n| a2 | b2 | c2 |\n| a3 | b3 | c3 |"
+ cut, truncated := truncateCharsLine(body, 60)
+ if !truncated {
+ t.Fatalf("expected a cut at 60 chars of a %d-char body", utf8.RuneCountInString(body))
+ }
+ for _, line := range strings.Split(body, "\n") {
+ if strings.Contains(cut, line) {
+ continue
+ }
+ if strings.HasPrefix(line, cut) && cut != "" && !strings.HasSuffix(cut, line) {
+ t.Fatalf("a partial line survived the cut:\n%q", cut)
+ }
+ }
+ // Every line in the result must appear whole in the source.
+ sourceLines := map[string]bool{}
+ for _, line := range strings.Split(body, "\n") {
+ sourceLines[line] = true
+ }
+ for _, line := range strings.Split(cut, "\n") {
+ if !sourceLines[line] {
+ t.Fatalf("returned line %q is not a whole source line; the cut landed mid-line:\n%s", line, cut)
+ }
+ }
+ if utf8.RuneCountInString(cut) > 60 {
+ t.Errorf("cut kept %d chars, over the 60 limit", utf8.RuneCountInString(cut))
+ }
+}
+
+func TestTruncateCharsLine_NoCutWhenUnderLimit(t *testing.T) {
+ body := "one\ntwo\nthree"
+ got, truncated := truncateCharsLine(body, 100)
+ if truncated || got != body {
+ t.Fatalf("under-limit body was altered: got=%q truncated=%v", got, truncated)
+ }
+}
+
+func TestWriteTextResponse_MarkdownPlainFormatIsTextMarkdown(t *testing.T) {
+ extraction := textExtraction{Text: "# Heading\n\nBody text.", Mode: extractionMarkdown}
+ w := textResponseRecorder(t, extraction, -1, "text")
+
+ if got := w.Header().Get("Content-Type"); got != "text/markdown; charset=utf-8" {
+ t.Errorf("Content-Type = %q, want text/markdown", got)
+ }
+ if w.Body.String() != "# Heading\n\nBody text." {
+ t.Errorf("body = %q, want the bare Markdown", w.Body.String())
+ }
+ if got := w.Header().Get(headerTextExtraction); got != extractionMarkdown {
+ t.Errorf("%s = %q, want %q", headerTextExtraction, got, extractionMarkdown)
+ }
+}
+
+func TestWriteTextResponse_MarkdownEnvelopeCarriesTitleAndDescription(t *testing.T) {
+ extraction := textExtraction{
+ Text: "## Section\n\n| a | b |\n|---|---|\n| 1 | 2 |",
+ Mode: extractionMarkdown,
+ Title: "Converter Title",
+ Description: "Converter description.",
+ }
+ w := textResponseRecorder(t, extraction, -1, "")
+ envelope := decodeTextEnvelope(t, w)
+
+ if envelope["extraction"] != extractionMarkdown {
+ t.Errorf("extraction = %v, want %q", envelope["extraction"], extractionMarkdown)
+ }
+ if envelope["title"] != "Converter Title" {
+ t.Errorf("title = %v, want the converter title", envelope["title"])
+ }
+ if envelope["description"] != "Converter description." {
+ t.Errorf("description = %v, want the converter description", envelope["description"])
+ }
+ if _, ok := envelope["rawLength"]; ok {
+ t.Errorf("rawLength present for a markdown response with no raw comparison")
+ }
+}
+
+// maxChars over a Markdown table: the JSON textLength counts the truncated body
+// and the last line stays a whole table row.
+func TestWriteTextResponse_MarkdownMaxCharsCutsOnLineBoundary(t *testing.T) {
+ body := "| Col A | Col B |\n|-------|-------|\n| a1 | b1 |\n| a2 | b2 |\n| a3 | b3 |"
+ extraction := textExtraction{Text: body, Mode: extractionMarkdown}
+ w := textResponseRecorder(t, extraction, 40, "")
+ envelope := decodeTextEnvelope(t, w)
+
+ if envelope["truncated"] != true {
+ t.Fatalf("truncated = %v, want true", envelope["truncated"])
+ }
+ text, _ := envelope["text"].(string)
+ for _, line := range strings.Split(text, "\n") {
+ if !strings.Contains(body, line) {
+ t.Fatalf("returned line %q is not a whole source line", line)
+ }
+ }
+ if envelope["textLength"] != float64(utf8.RuneCountInString(text)) {
+ t.Errorf("textLength = %v, want the truncated body length %d", envelope["textLength"], utf8.RuneCountInString(text))
+ }
+}
+
+// The guard runs on markdown exactly as on readability: reuse the injected
+// corpus the /text and /html guard tests share and assert the same warn-and-wrap.
+func TestWriteTextResponse_MarkdownReusesTheTextGuard(t *testing.T) {
+ h := inspectIDPIHandlers(false)
+ h.Bridge = &mockBridge{}
+
+ for _, mode := range []string{extractionReadability, extractionMarkdown} {
+ w := httptest.NewRecorder()
+ r := httptest.NewRequest("GET", "/text", nil)
+ h.writeTextResponse(w, r, context.Background(), textExtraction{Text: injectedMarkup, Mode: mode}, -1, "", nil, nil)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("mode %q: status = %d, want 200 (warn, not block) body=%s", mode, w.Code, w.Body.String())
+ }
+ envelope := decodeTextEnvelope(t, w)
+ if envelope["idpiWarning"] == nil || envelope["idpiWarning"] == "" {
+ t.Errorf("mode %q: idpiWarning missing; the guard did not run on the body", mode)
+ }
+ text, _ := envelope["text"].(string)
+ if !strings.Contains(text, "untrusted_web_content") {
+ t.Errorf("mode %q: body is not wrapped as untrusted content:\n%s", mode, text)
+ }
+ }
+}
diff --git a/internal/scrape/run.go b/internal/scrape/run.go
index d41193c7..bf7d17dd 100644
--- a/internal/scrape/run.go
+++ b/internal/scrape/run.go
@@ -252,6 +252,30 @@ func Run(ctx context.Context, input Input, opts RunOptions, crawl Crawler, rende
}, nil
}
+// PageMarkdown is one rendered document converted to Markdown through
+// seaportal: the body with the title and description the converter recovered,
+// plus its error. Markdown is empty when the converter errored or produced no
+// content, so a caller can fall back to raw text.
+type PageMarkdown struct {
+ Markdown string
+ Title string
+ Description string
+ Err string
+}
+
+// ToMarkdown converts one document's HTML to Markdown through the seaportal
+// engine. Markdown is blank when the converter errors or yields no content;
+// Title, Description and Err are always reported. It is the single owner of the
+// (html, url) → Markdown conversion shared by enrichPage and the /text handler.
+func ToMarkdown(html, url string) PageMarkdown {
+ r := seaportal.FromHTML(html, url)
+ md := PageMarkdown{Title: r.Title, Description: r.Description, Err: r.Error}
+ if strings.TrimSpace(r.Content) != "" {
+ md.Markdown = r.Content
+ }
+ return md
+}
+
// enrichPage renders p in the browser and replaces its content with the
// extraction over the rendered HTML. The HTTP extraction is kept whenever
// the browser path fails or yields nothing.
@@ -261,25 +285,25 @@ func enrichPage(p *Page, render BrowserRenderer) {
p.BrowserError = err.Error()
return
}
- r := seaportal.FromHTML(html, p.URL)
- if r.Error != "" {
- p.BrowserError = r.Error
+ md := ToMarkdown(html, p.URL)
+ if md.Err != "" {
+ p.BrowserError = md.Err
return
}
- if strings.TrimSpace(r.Content) == "" {
+ if md.Markdown == "" {
p.BrowserError = "browser extraction produced no content"
return
}
- p.Markdown = r.Content
+ p.Markdown = md.Markdown
p.Source = SourceBrowser
// The browser reached the page and produced content, so an HTTP fetch
// failure no longer marks the page as failed.
p.Error = ""
- if r.Title != "" {
- p.Title = r.Title
+ if md.Title != "" {
+ p.Title = md.Title
}
- if p.Meta == nil && r.Description != "" {
- p.Meta = map[string]string{"description": r.Description}
+ if p.Meta == nil && md.Description != "" {
+ p.Meta = map[string]string{"description": md.Description}
}
}
diff --git a/internal/scrape/run_test.go b/internal/scrape/run_test.go
index 5ee17048..b3694eec 100644
--- a/internal/scrape/run_test.go
+++ b/internal/scrape/run_test.go
@@ -735,3 +735,23 @@ func TestAnUnrecognisedInheritedRecommendationIsForwardedNotDropped(t *testing.T
t.Errorf("an inherited recommendation matching neither the regenerated phrases nor the sitemap lines was silently swallowed; the recorded rule says unrecognised advice FORWARDS, since dropping advice that is still true is the worse failure\n got %v", report.Summary.Recommendations)
}
}
+
+func TestToMarkdownConvertsRenderedHTML(t *testing.T) {
+ md := ToMarkdown(renderedHTML, "https://example.com/page")
+ if md.Err != "" {
+ t.Fatalf("unexpected converter error: %s", md.Err)
+ }
+ if md.Title != "Rendered Title" {
+ t.Errorf("Title = %q, want the converter title", md.Title)
+ }
+ if strings.TrimSpace(md.Markdown) == "" {
+ t.Error("Markdown is empty for a rich rendered document")
+ }
+}
+
+func TestToMarkdownEmptyForContentlessDocument(t *testing.T) {
+ md := ToMarkdown("<html><body></body></html>", "https://example.com/empty")
+ if md.Markdown != "" {
+ t.Errorf("Markdown = %q, want empty so the caller falls back", md.Markdown)
+ }
+}
diff --git a/tests/e2e/fixtures/markdown.html b/tests/e2e/fixtures/markdown.html
new file mode 100644
index 00000000..1e03a248
--- /dev/null
+++ b/tests/e2e/fixtures/markdown.html
@@ -0,0 +1,52 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <title>Markdown Fixture</title>
+ <meta name="description" content="A page that converts cleanly to Markdown.">
+</head>
+<body>
+ <article>
+ <h1>Markdown Fixture</h1>
+
+ <h2>First Section</h2>
+ <p>
+ This paragraph carries an
+ <a href="https://example.com/link">inline link</a>
+ and enough surrounding prose that the readability extractor keeps it as
+ the article body rather than discarding it as a thin fragment of the page.
+ </p>
+
+ <h2>Second Section</h2>
+ <ul>
+ <li>Alpha item describing the first point in the list</li>
+ <li>Beta item describing the second point in the list</li>
+ <li>Gamma item describing the third point in the list</li>
+ </ul>
+
+ <table>
+ <thead>
+ <tr><th>Column A</th><th>Column B</th><th>Column C</th></tr>
+ </thead>
+ <tbody>
+ <tr><td>a1</td><td>b1</td><td>c1</td></tr>
+ <tr><td>a2</td><td>b2</td><td>c2</td></tr>
+ <tr><td>a3</td><td>b3</td><td>c3</td></tr>
+ </tbody>
+ </table>
+
+ <p>
+ A closing paragraph so the extracted article sits comfortably above any
+ thin-content threshold the converter applies before it returns Markdown.
+ </p>
+ </article>
+
+ <iframe
+ id="md-frame"
+ title="md-frame"
+ src="iframe-content.html"
+ width="600"
+ height="300"
+ ></iframe>
+</body>
+</html>
diff --git a/tests/e2e/scenarios/api/text-markdown-basic.sh b/tests/e2e/scenarios/api/text-markdown-basic.sh
new file mode 100755
index 00000000..e88fe488
--- /dev/null
+++ b/tests/e2e/scenarios/api/text-markdown-basic.sh
@@ -0,0 +1,148 @@
+#!/bin/bash
+# text-markdown-basic.sh — GET /text?mode=markdown: page-to-Markdown conversion,
+# format/content-type, line-boundary truncation, frame scope, refusal, and the
+# IDPI guard parity with the readability path.
+
+GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${GROUP_DIR}/../../helpers/api.sh"
+
+# ─────────────────────────────────────────────────────────────────
+start_test "markdown: GET /text?mode=markdown returns converter Markdown"
+
+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/markdown.html\"}"
+assert_ok "navigate to markdown.html"
+
+pt_get "/text?mode=markdown"
+assert_ok "text markdown"
+assert_json_eq "$RESULT" '.extraction' 'markdown' "extraction echoes markdown"
+
+TITLE=$(echo "$RESULT" | jq -r '.title')
+if [ -n "$TITLE" ] && [ "$TITLE" != "null" ]; then
+ echo -e " ${GREEN}✓${NC} title present ($TITLE)"
+ ((ASSERTIONS_PASSED++)) || true
+else
+ echo -e " ${RED}✗${NC} title missing"
+ ((ASSERTIONS_FAILED++)) || true
+fi
+
+BODY=$(echo "$RESULT" | jq -r '.text')
+assert_contains "$BODY" "# " "heading survives as Markdown"
+assert_contains "$BODY" "## " "subheading survives as Markdown"
+assert_contains "$BODY" "](https://example.com/link)" "inline link survives as Markdown"
+assert_contains "$BODY" "- " "list item survives as Markdown"
+assert_contains "$BODY" "|" "table survives as Markdown"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "markdown: format=text returns text/markdown content type"
+
+RESPONSE=$(e2e_curl -s -w "\n%{http_code}\n%{content_type}" "${E2E_SERVER}/text?mode=markdown&format=text")
+STATUS=$(echo "$RESPONSE" | tail -n 2 | head -1)
+CTYPE=$(echo "$RESPONSE" | tail -n 1)
+
+HTTP_STATUS="$STATUS"; assert_http_status 200 "format=text returned 200"
+if echo "$CTYPE" | grep -q "text/markdown"; then
+ echo -e " ${GREEN}✓${NC} content-type is text/markdown"
+ ((ASSERTIONS_PASSED++)) || true
+else
+ echo -e " ${RED}✗${NC} content-type is $CTYPE (expected text/markdown)"
+ ((ASSERTIONS_FAILED++)) || true
+fi
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "markdown: maxChars truncates on a line boundary"
+
+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.
+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
+ [ -z "$line" ] && continue
+ if ! grep -Fqx -- "$line" <<<"$FULL"; then
+ PARTIAL_LINE=1
+ echo -e " ${RED}✗${NC} line not whole: $line"
+ fi
+done <<<"$CUT"
+if [ "$PARTIAL_LINE" -eq 0 ]; then
+ echo -e " ${GREEN}✓${NC} every truncated line is a complete source line"
+ ((ASSERTIONS_PASSED++)) || true
+else
+ ((ASSERTIONS_FAILED++)) || true
+fi
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "markdown: frame scope converts the selected iframe"
+
+pt_post /frame -d '{"target":"#md-frame"}'
+assert_ok "select iframe scope"
+assert_json_eq "$RESULT" '.scoped' 'true' "frame scope enabled"
+
+pt_get "/text?mode=markdown"
+assert_ok "frame-scoped markdown"
+FRAME_BODY=$(echo "$RESULT" | jq -r '.text')
+assert_contains "$FRAME_BODY" "Card number" "iframe document converted, not the parent"
+assert_not_contains "$FRAME_BODY" "Markdown Fixture" "parent article excluded from frame scope"
+
+pt_post /frame -d '{"target":"main"}'
+assert_ok "reset frame scope"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "markdown: unknown mode is refused with a 400"
+
+pt_get "/text?mode=bogus"
+assert_http_status 400 "unknown mode refused"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "markdown: IDPI guard applies as on the readability path"
+
+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/idpi-inject.html\"}"
+assert_ok "navigate to idpi-inject.html"
+
+# Warn mode (default api service): the request is answered and the advisory
+# rides on the X-IDPI-Warning header and the idpiWarning body field, identical
+# to the readability path on the same page.
+TMPH=$(mktemp)
+RESPONSE=$(e2e_curl -s -w "\n%{http_code}" -D "$TMPH" "${E2E_SERVER}/text?mode=markdown")
+MD_STATUS=$(echo "$RESPONSE" | tail -n 1)
+MD_BODY=$(echo "$RESPONSE" | head -n -1)
+MD_WARN_HDR=$(grep -i "^X-IDPI-Warning:" "$TMPH" | sed 's/^[^:]*: *//' | tr -d '\r' | head -1)
+rm -f "$TMPH"
+
+HTTP_STATUS="$MD_STATUS"; assert_http_status 200 "markdown returns in warn mode"
+if [ -n "$MD_WARN_HDR" ]; then
+ echo -e " ${GREEN}✓${NC} X-IDPI-Warning header present"
+ ((ASSERTIONS_PASSED++)) || true
+else
+ echo -e " ${RED}✗${NC} X-IDPI-Warning header missing"
+ ((ASSERTIONS_FAILED++)) || true
+fi
+assert_json_exists "$MD_BODY" ".idpiWarning" "idpiWarning field in markdown body"
+
+# Parity: the readability path warns on the same page.
+TMPH2=$(mktemp)
+e2e_curl -s -D "$TMPH2" "${E2E_SERVER}/text" >/dev/null
+RD_WARN_HDR=$(grep -i "^X-IDPI-Warning:" "$TMPH2" | sed 's/^[^:]*: *//' | tr -d '\r' | head -1)
+rm -f "$TMPH2"
+if [ -n "$RD_WARN_HDR" ]; then
+ echo -e " ${GREEN}✓${NC} readability path warns identically on the same page"
+ ((ASSERTIONS_PASSED++)) || true
+else
+ echo -e " ${RED}✗${NC} readability path did not warn; guard parity broken"
+ ((ASSERTIONS_FAILED++)) || true
+fi
+
+end_test
diff --git a/tests/e2e/scenarios/manifest.json b/tests/e2e/scenarios/manifest.json
index ef4f459d..5aa8f3ca 100644
--- a/tests/e2e/scenarios/manifest.json
+++ b/tests/e2e/scenarios/manifest.json
@@ -43,6 +43,13 @@
"pr"
]
},
+ "api/text-markdown-basic.sh": {
+ "tags": [
+ "text",
+ "markdown",
+ "pr"
+ ]
+ },
"api/browser-extended.sh": {
"tags": [
"browser",