High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: default /text extraction fuses adjacent fields, so a status code and timestamp return as one unparseable number (PIN-197)
Luigi Agosti75e1208717f2
diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.goindex aedd8cc5..7a9c7906 100644--- a/cmd/pinchtab/cmd_cli_register.go+++ b/cmd/pinchtab/cmd_cli_register.go@@ -170,7 +170,7 @@ func configureBrowserFlags() {findCmd.Flags().Bool("ref-only", false, "Output just the element ref")textCmd.Flags().Bool("raw", false, "Raw extraction mode (alias of --full)")- textCmd.Flags().Bool("full", false, "Return the full page text (document.body.innerText) instead of the default Readability-filtered content")+ textCmd.Flags().Bool("full", false, "Return the full page text (document.body.innerText, the API's mode=full/mode=raw) instead of the default Readability-filtered content")textCmd.Flags().String("frame", "", "Extract text from a specific iframe by frameId. If unset, uses the tab's active frame scope (set via `pinchtab frame`) or the top-level document.")textCmd.Flags().StringP("selector", "s", "", "Element selector to extract text from (ref/CSS/XPath/text)")textCmd.Flags().Bool("json", false, "Output full JSON response instead of just text content")diff --git a/docs/endpoints.md b/docs/endpoints.mdindex 62107a42..e76b5b8c 100644--- a/docs/endpoints.md+++ b/docs/endpoints.md@@ -241,7 +241,7 @@ Snapshot query parameters:Text query parameters:-- `mode=raw`+- `mode=raw` (`mode=full` is an alias; any other value is a 400 naming the accepted ones)- `format`- `maxChars`- `frameId`@@ -251,6 +251,12 @@ Text query parameters:full `innerText`, or `/snapshot` for structured UI text like prices and buttonlabels.+`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+adjacent blocks by a newline, so a status code and a timestamp in neighbouring+cells stay two fields rather than one number.+`/text` is also frame-aware. `frameId` targets a specific iframe for a one-shotread; otherwise the endpoint inherits the tab's current `/frame` scope.diff --git a/internal/assets/readability.js b/internal/assets/readability.jsindex b531e1f3..e2fa220e 100644--- a/internal/assets/readability.js+++ b/internal/assets/readability.js@@ -43,5 +43,61 @@root.querySelectorAll('script, style, noscript, svg, [hidden]').forEach(el => el.remove());- return root.innerText.replace(/\n{3,}/g, '\n\n').trim();+ // root is always a CLONE, so it is detached, and innerText on an unrendered node+ // has no layout to consult — it degrades to textContent, which concatenates+ // descendant text with no separator at all. That is how a status cell and a+ // timestamp cell came back as one unparseable number, and how two adjacent+ // paragraphs came back as one word.+ //+ // serialize walks the clone instead and supplies the boundaries layout would+ // have: a newline between blocks, a tab between table cells. It inserts a+ // separator ONLY where the text either side would otherwise fuse, so a document+ // whose source already carries whitespace between its tags serialises exactly as+ // it did before and nothing reflows.+ //+ // Every mutation above and every read below happen on the clone, which is never+ // inserted into the document — that is what guarantees a read cannot alter the+ // page an agent is driving. Do not "fix" this by attaching the clone off-screen+ // to give it layout: that fires the page's mutation observers and re-requests+ // every image and iframe in the copy.+ const BLOCKS = new Set(['ADDRESS', 'ARTICLE', 'ASIDE', 'BLOCKQUOTE', 'DD', 'DETAILS',+ 'DIALOG', 'DIV', 'DL', 'DT', 'FIELDSET', 'FIGCAPTION', 'FIGURE', 'FOOTER', 'FORM',+ 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'HEADER', 'HGROUP', 'HR', 'LI', 'MAIN', 'NAV',+ 'OL', 'P', 'PRE', 'SECTION', 'TABLE', 'TBODY', 'TFOOT', 'THEAD', 'TR', 'UL']);++ let out = '';+ let pending = '';+ // A boundary QUEUES a separator rather than writing one. It is written only when the+ // next text arrives with nothing separating it from what came before — which is what+ // keeps a document that already spaces its tags byte-identical to the old output. A+ // newline outranks a tab, so the first cell of a row starts a line rather than+ // continuing one.+ const queue = (sep) => {+ if (sep === '\n' || pending === '') pending = sep;+ };+ const write = (data) => {+ if (data === '') return;+ if (pending && out !== '' && !/\s$/.test(out) && !/^\s/.test(data)) out += pending;+ pending = '';+ out += data;+ };+ const serialize = (node) => {+ if (node.nodeType === Node.TEXT_NODE) {+ write(node.data);+ return;+ }+ if (node.nodeType !== Node.ELEMENT_NODE) return;+ if (node.tagName === 'BR') {+ queue('\n');+ return;+ }+ const block = BLOCKS.has(node.tagName);+ if (block) queue('\n');+ if (node.tagName === 'TD' || node.tagName === 'TH') queue('\t');+ for (const child of node.childNodes) serialize(child);+ if (block) queue('\n');+ };+ serialize(root);++ return out.replace(/\n{3,}/g, '\n\n').trim();})()diff --git a/internal/assets/readability_browser_test.go b/internal/assets/readability_browser_test.gonew file mode 100644index 00000000..9bed7a55--- /dev/null+++ b/internal/assets/readability_browser_test.go@@ -0,0 +1,216 @@+package assets_test++import (+ "context"+ "encoding/base64"+ "strings"+ "testing"+ "time"++ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/assets"+ "github.com/pinchtab/pinchtab/internal/testbrowser"+)++// The extraction runs in a browser, so it is proven in one. A Go-level test can only+// drive the handler's mock, which returns whatever string it was handed and can never+// see what the script does to a DOM.+func readabilityPage(t *testing.T, html string) context.Context {+ t.Helper()++ chromePath := testbrowser.Path(t)+ profile := testbrowser.ProfileDir(t)+ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(+ chromedp.DefaultExecAllocatorOptions[:],+ chromedp.ExecPath(chromePath),+ chromedp.UserDataDir(profile),+ chromedp.Flag("headless", true),+ chromedp.Flag("no-sandbox", true),+ )...)+ ctx, cancelBrowser := chromedp.NewContext(alloc)+ ctx, cancelTimeout := context.WithTimeout(ctx, 30*time.Second)+ t.Cleanup(func() {+ cancelTimeout()+ cancelBrowser()+ cancelAlloc()+ })++ if err := chromedp.Run(ctx, chromedp.Navigate("data:text/html;base64,"+base64.StdEncoding.EncodeToString([]byte(html)))); err != nil {+ t.Fatal(err)+ }+ return ctx+}++func extractReadability(t *testing.T, ctx context.Context) string {+ t.Helper()+ var text string+ if err := chromedp.Run(ctx, chromedp.Evaluate(assets.ReadabilityJS, &text)); err != nil {+ t.Fatal(err)+ }+ return text+}++// The reported document: a status code and a timestamp in adjacent cells came back as+// one unparseable number, and two adjacent paragraphs came back as one word. The source+// carries no whitespace between the tags, which is what every JS-rendered dashboard,+// search result and log view looks like.+const fusedFieldsPage = `<table><thead><tr><th>Code</th><th>Time</th><th>Path</th></tr></thead>` ++ `<tbody><tr><td>200</td><td>09:38:14</td><td>/health</td></tr>` ++ `<tr><td>404</td><td>10:01:02</td><td>/missing</td></tr></tbody></table>` ++ `<ul><li>alpha</li><li>beta</li></ul><p>para one</p><p>para two</p>`++func TestDefaultExtractionKeepsAdjacentFieldsApart(t *testing.T) {+ text := extractReadability(t, readabilityPage(t, fusedFieldsPage))++ for _, fused := range []string{"20009:38:14", "40410:01:02", "alphabeta", "para onepara two", "CodeTimePath"} {+ if strings.Contains(text, fused) {+ t.Errorf("the extraction still fuses %q, so the field boundary is gone and cannot be recovered:\n%s", fused, text)+ }+ }+ for _, field := range []string{"200", "09:38:14", "/health", "alpha", "beta", "para one", "para two"} {+ if !strings.Contains(text, field) {+ t.Errorf("%q is missing from the extraction; separating the fields must not drop any:\n%s", field, text)+ }+ }+}++// The cheapest permanent guard, and the one the defect would have failed: two adjacent+// block elements must never serialise with nothing between them. Asserted on the DEFAULT+// mode, since that is the one nobody has to opt into.+func TestTwoAdjacentBlocksNeverSerialiseWithNoSeparator(t *testing.T) {+ for _, tag := range []string{"p", "div", "li", "h2", "section", "td"} {+ t.Run(tag, func(t *testing.T) {+ body := "<" + tag + ">alpha</" + tag + "><" + tag + ">beta</" + tag + ">"+ if tag == "td" {+ body = "<table><tbody><tr>" + body + "</tr></tbody></table>"+ }+ text := extractReadability(t, readabilityPage(t, body))++ if !strings.Contains(text, "alpha") || !strings.Contains(text, "beta") {+ t.Fatalf("fixture did not survive extraction: %q", text)+ }+ if strings.Contains(text, "alphabeta") {+ t.Errorf("two adjacent <%s> serialised with zero separator: %q", tag, text)+ }+ })+ }+}++// A separator is inserted ONLY where the text either side would otherwise fuse, so a+// document whose source already carries whitespace between its tags is untouched. The+// oracle is the extraction this replaced — clone, strip, read as textContent — computed+// in the page, so the claim is measured rather than asserted against a hand-typed string.+const previousExtraction = `(() => {+ const root = document.body.cloneNode(true);+ root.querySelectorAll('script, style, noscript, svg, [hidden]').forEach(el => el.remove());+ return root.textContent.replace(/\n{3,}/g, '\n\n').trim();+})()`++func TestASourceThatAlreadySeparatesItsBlocksIsUnchanged(t *testing.T) {+ prettyPrinted := `<div>+ <h1>Title</h1>+ <p>First paragraph.</p>+ <p>Second paragraph.</p>+ <ul>+ <li>alpha</li>+ <li>beta</li>+ </ul>+</div>`+ ctx := readabilityPage(t, prettyPrinted)++ var before string+ if err := chromedp.Run(ctx, chromedp.Evaluate(previousExtraction, &before)); err != nil {+ t.Fatal(err)+ }+ after := extractReadability(t, ctx)++ if before == "" {+ t.Fatal("the oracle extracted nothing, so this comparison would pass vacuously")+ }+ if after != before {+ t.Errorf("a body with whitespace already between its blocks changed:\n before %q\n after %q", before, after)+ }+}++// Whatever else it does, the extraction only ADDS whitespace: no character of the text+// is dropped, reordered or rewritten. That is what makes the change safe to default on,+// and it holds for the fused document too, where the output differs the most.+func TestTheExtractionOnlyInsertsWhitespace(t *testing.T) {+ ctx := readabilityPage(t, fusedFieldsPage)++ var before string+ if err := chromedp.Run(ctx, chromedp.Evaluate(previousExtraction, &before)); err != nil {+ t.Fatal(err)+ }+ after := extractReadability(t, ctx)++ if squeeze(before) == "" {+ t.Fatal("the oracle extracted nothing, so this comparison would pass vacuously")+ }+ if squeeze(after) != squeeze(before) {+ t.Errorf("the extraction changed more than the whitespace:\n before %q\n after %q", squeeze(before), squeeze(after))+ }+ if after == before {+ t.Error("the fused document extracted identically, so this fixture no longer exercises the defect")+ }+}++func squeeze(s string) string {+ return strings.Join(strings.Fields(s), "")+}++// The CI twin. Every guard above needs a browser and skips without one, so a revert of+// the fix would land green on a machine that has none. This one reds anywhere: the whole+// defect was reading innerText off a node that has no layout, so the script must not read+// innerText from its clone at all, and must carry the walk that replaced it.+func TestTheScriptDoesNotReadInnerTextFromTheDetachedClone(t *testing.T) {+ if strings.Contains(assets.ReadabilityJS, "root.innerText") {+ t.Error("the script reads innerText from the clone again; the clone is detached, so innerText has no layout to consult and silently degrades to textContent — every field boundary is lost. Serialise the clone instead")+ }+ for _, required := range []string{"BLOCKS", "queue(", "serialize("} {+ if !strings.Contains(assets.ReadabilityJS, required) {+ t.Errorf("the separator-aware walk is gone (%q not found); without it adjacent blocks and table cells fuse — re-point this guard at whatever replaced the walk rather than deleting it", required)+ }+ }+}++// A read must not alter the page under an agent. This watches for mutations DURING the+// extraction rather than comparing the document before and after: the tempting alternative+// fix — attach the clone off-screen so it gets layout, read innerText, remove it — restores+// the document perfectly and a before/after comparison cannot see it, while the page's own+// observers fire and every image and iframe in the copy is re-requested.+var observedExtraction = `(() => {+ const seen = new MutationObserver(() => {});+ seen.observe(document, {subtree: true, childList: true, attributes: true, characterData: true});+ const text = ` + assets.ReadabilityJS + `;+ const records = seen.takeRecords();+ seen.disconnect();+ return records.length + ':' + text.length;+})()`++func TestExtractionMutatesNothingInTheLivePage(t *testing.T) {+ ctx := readabilityPage(t, `<nav>skip me</nav><main><p>alpha</p><p>beta</p></main><footer>gone</footer>`)++ var beforeHTML, observed, afterHTML string+ if err := chromedp.Run(ctx,+ chromedp.Evaluate(`document.documentElement.outerHTML`, &beforeHTML),+ chromedp.Evaluate(observedExtraction, &observed),+ chromedp.Evaluate(`document.documentElement.outerHTML`, &afterHTML),+ ); err != nil {+ t.Fatal(err)+ }++ if !strings.Contains(beforeHTML, "skip me") {+ t.Fatal("the fixture never had the stripped nodes, so an in-place strip would not show here")+ }+ mutations, extractedLen, _ := strings.Cut(observed, ":")+ if extractedLen == "0" || extractedLen == "" {+ t.Fatalf("the extraction returned nothing, so this guard checked nothing: %q", observed)+ }+ if mutations != "0" {+ t.Errorf("the extraction made %s mutation records against the live document; a read must not alter the page an agent is driving — strip and serialise a detached clone instead of attaching one", mutations)+ }+ if afterHTML != beforeHTML {+ t.Errorf("the live DOM did not survive a read:\n before %q\n after %q", beforeHTML, afterHTML)+ }+}diff --git a/internal/handlers/text.go b/internal/handlers/text.goindex e29f922c..63b6459f 100644--- a/internal/handlers/text.go+++ b/internal/handlers/text.go@@ -4,6 +4,7 @@ import ("context""fmt""net/http"+ "sort""strconv""strings""time"@@ -31,7 +32,11 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {return}- mode := r.URL.Query().Get("mode")+ mode, modeErr := resolveTextMode(r.URL.Query().Get("mode"))+ if modeErr != nil {+ httpx.Error(w, 400, modeErr)+ return+ }format := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("format")))maxChars := -1if v := r.URL.Query().Get("maxChars"); v != "" {@@ -125,6 +130,43 @@ func (h *Handlers) writeElementTextResponse(w http.ResponseWriter, r *http.Requeconst rawTextScript = `document.body.innerText`+// textModes are the values ?mode= accepts, each mapped to the extraction it selects.+// "full" is an ALIAS of raw because that is what the CLI's --full already sends and+// what the word plainly reads as — the whole unfiltered page. It used to fall through+// 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",+}++// resolveTextMode maps a requested mode onto the extraction that runs, and REFUSES an+// unimplemented one. Silently extracting readability for a mode nobody implemented hands+// the caller something other than what they asked for with no signal, which is the same+// defect class as losing a field boundary.+func resolveTextMode(requested string) (string, error) {+ normalized := strings.ToLower(strings.TrimSpace(requested))+ mode, ok := textModes[normalized]+ if !ok {+ return "", fmt.Errorf("unknown text mode %q; accepted values are %s (omit mode for the default Readability extraction)", requested, strings.Join(namedTextModes(), ", "))+ }+ return mode, nil+}++// namedTextModes lists the modes a caller can spell, sorted so the refusal reads the+// same on every run rather than however the map happened to iterate.+func namedTextModes() []string {+ named := make([]string, 0, len(textModes))+ for mode := range textModes {+ if mode != "" {+ named = append(named, mode)+ }+ }+ sort.Strings(named)+ return named+}+// Extraction modes echoed to the caller: which extractor produced the text.const (extractionReadability = "readability"diff --git a/internal/handlers/text_test.go b/internal/handlers/text_test.goindex 5209e4b4..0fea9b14 100644--- a/internal/handlers/text_test.go+++ b/internal/handlers/text_test.go@@ -141,6 +141,76 @@ func TestExtractDocumentText_ArticleKeepsReadabilityOutput(t *testing.T) {}}+// The same word selected opposite behaviour on the two surfaces: the CLI's --full sends+// mode=raw and returns innerText, while the API's ?mode=full fell through to readability.+// full is now the alias the CLI already implies, and a mode nobody implemented is refused+// rather than silently downgraded.+func TestResolveTextMode(t *testing.T) {+ for _, tc := range []struct {+ requested string+ want string+ }{+ {"", ""},+ {"raw", "raw"},+ {"full", "raw"},+ {"FULL", "raw"},+ {" raw ", "raw"},+ } {+ got, err := resolveTextMode(tc.requested)+ if err != nil {+ t.Errorf("resolveTextMode(%q) refused: %v", tc.requested, err)+ continue+ }+ if got != tc.want {+ t.Errorf("resolveTextMode(%q) = %q, want %q", tc.requested, got, tc.want)+ }+ }+}++func TestResolveTextMode_RefusesAnUnimplementedMode(t *testing.T) {+ _, err := resolveTextMode("readable")+ if err == nil {+ t.Fatal("an unimplemented mode was accepted; the caller gets readability while believing they asked for something else")+ }+ message := err.Error()+ if !strings.Contains(message, `"readable"`) {+ t.Errorf("the refusal does not name what the caller sent: %s", message)+ }+ for _, accepted := range []string{"full", "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") {+ t.Errorf("the accepted values are not in a stable order, so the refusal differs between runs: %s", message)+ }+}++// full must be byte-identical to raw, not merely close: the two are the same extraction.+func TestExtractDocumentText_FullIsTheSameExtractionAsRaw(t *testing.T) {+ extractions := map[string]textExtraction{}+ for _, requested := range []string{"raw", "full"} {+ mode, err := resolveTextMode(requested)+ if err != nil {+ t.Fatalf("resolveTextMode(%q): %v", requested, err)+ }+ m := textScriptBridge(t, collapsedReadabilityText, landingPageRawText)+ h := New(m, &config.RuntimeConfig{}, nil, nil, nil)+ extraction, err := h.extractDocumentText(context.Background(), mode, "")+ if err != nil {+ t.Fatalf("extractDocumentText(%q): %v", requested, err)+ }+ extractions[requested] = extraction+ }++ if extractions["full"] != extractions["raw"] {+ t.Errorf("?mode=full and ?mode=raw produced different extractions:\n full %+v\n raw %+v", extractions["full"], extractions["raw"])+ }+ if extractions["raw"].Text != landingPageRawText {+ t.Errorf("raw extraction = %q, want the raw document text unchanged", extractions["raw"].Text)+ }+}+func TestExtractDocumentText_RawModeSkipsCoverageComparison(t *testing.T) {m := textScriptBridge(t, collapsedReadabilityText, landingPageRawText)h := New(m, &config.RuntimeConfig{}, nil, nil, nil)